Created
July 27, 2014 19:55
-
-
Save supr/7e1f5a1eefc885491f03 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> | |
#include <string> | |
using namespace std; | |
template<typename T> | |
struct Node { | |
T item; | |
struct Node<T> *next; | |
}; | |
template<typename T> | |
class List | |
{ | |
private: | |
struct Node<T> *head; | |
struct Node<T> *tail; | |
public: | |
List() { | |
head = nullptr; | |
tail = nullptr; | |
} | |
~List() { | |
while(head) { | |
Node<T> *tmp = head; | |
head = head->next; | |
delete tmp; | |
} | |
} | |
void print(void); | |
void print_reverse(void); | |
void insert(T data); | |
}; | |
template<typename T> | |
void List<T>::insert(T data) { | |
Node<T> * newNode = new Node<T>; | |
newNode->item = data; | |
newNode->next = nullptr; | |
if(!head) { | |
head = newNode; | |
tail = newNode; | |
} else { | |
tail->next = newNode; | |
tail = newNode; | |
} | |
} | |
template<typename T> | |
void List<T>::print(void) { | |
Node<T>* tmp = head; | |
while(tmp) { | |
std::cout << tmp->item << " "; //std::endl; | |
tmp = tmp->next; | |
} | |
std::cout << std::endl; | |
} | |
template<typename T> | |
void List<T>::print_reverse(void) { | |
Node<T>* tmp = tail; | |
while(tmp) { | |
std::cout << tmp->item << " "; // << std::endl; | |
Node<T> *thead = head; | |
while(thead && thead->next != tmp ) { | |
thead = thead->next; | |
} | |
tmp = thead; | |
} | |
std::cout << std::endl; | |
} | |
int main(void) { | |
List<int> l; | |
List<char> a; | |
l.insert(1); | |
l.insert(2); | |
l.insert(3); | |
l.insert(4); | |
a.insert('a'); | |
a.insert('b'); | |
a.insert('c'); | |
l.print(); | |
l.print_reverse(); | |
l.print(); | |
a.print(); | |
a.print_reverse(); | |
a.print(); | |
List<string> s; | |
s.insert("abc"); | |
s.insert("def"); | |
s.insert("ghi"); | |
s.print(); | |
s.print_reverse(); | |
s.print(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment