Last active
August 29, 2015 14:04
-
-
Save supr/701491a23c8f6eb458ea to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
template<typename T> | |
class Node { | |
public: | |
T data; | |
Node<T>* next; | |
}; | |
template<typename T> class List; | |
template<typename T> | |
class Stack { | |
private: | |
List<T>* data_; | |
public: | |
Stack() { | |
data_ = new List<T>; | |
} | |
~Stack() { | |
delete data_; | |
} | |
void push(T data); | |
T pop(); | |
void print(void); | |
}; | |
template<typename T> | |
class List { | |
friend class Stack<T>; | |
private: | |
Node<T> *head; | |
Node<T> *tail; | |
public: | |
List() { | |
head = tail = nullptr; | |
} | |
~List() { | |
while(head) { | |
Node<T>* tmp = head->next; | |
delete head; | |
head = tmp; | |
} | |
} | |
void insert(T data); | |
void print(void); | |
void remove(T data); | |
T pop(void); | |
}; | |
template<typename T> | |
void List<T>::insert(T data) { | |
if(!head) { | |
head = new Node<T>; | |
head->data = data; | |
tail = head; | |
} else { | |
tail->next = new Node<T>; | |
tail->next->data = data; | |
tail->next->next = nullptr; | |
tail = tail->next; | |
} | |
} | |
template<typename T> | |
void List<T>::print(void) { | |
Node<T> *tmp = head; | |
while(tmp) { | |
std::cout << tmp->data << " "; | |
tmp = tmp->next; | |
} | |
std::cout << std::endl; | |
} | |
template<typename T> | |
void List<T>::remove(T data) { | |
Node<T> *tmp = head; | |
Node<T> *prev = tmp; | |
while(tmp) { | |
if (tmp->data == data) { | |
if(tmp == head) { | |
head = tmp->next; | |
delete tmp; | |
} else { | |
prev->next = tmp->next; | |
delete tmp; | |
} | |
} | |
prev = tmp; | |
tmp = tmp->next; | |
} | |
} | |
template<typename T> | |
T List<T>::pop(void) { | |
Node<T> *prev = head; | |
Node<T> *tmp = head; | |
while(tmp->next) { | |
prev = tmp; | |
tmp = tmp->next; | |
} | |
tail = tmp; | |
T rv = tail->data; | |
delete tail; | |
tail = prev; | |
tail->next = nullptr; | |
//prev->next = nullptr; | |
return rv; | |
} | |
template<typename T> | |
void Stack<T>::push(T data) { | |
data_->insert(data); | |
} | |
template<typename T> | |
T Stack<T>::pop(void) { | |
return data_->pop(); | |
} | |
template<typename T> | |
void Stack<T>::print(void) { | |
return data_->print(); | |
} | |
int main(void) { | |
List<int> a; | |
for(int i=0; i < 10; i++) { | |
a.insert(i); | |
} | |
a.print(); | |
a.remove(5); | |
a.print(); | |
Stack<int> s; | |
for(int i=0; i<10; i++) { | |
s.push(i); | |
} | |
s.print(); | |
s.pop(); | |
s.pop(); | |
s.print(); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment