Advertisement
Guest User

Untitled

a guest
Mar 19th, 2014
308
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. class List
  2. {
  3. public:
  4.     struct Node
  5.     {
  6.         Node(const int& data, Node* next=0):data(data),next(next) {}
  7.         Node* next;
  8.         int data;
  9.     };
  10.  
  11.     List() : head(0) {}
  12.  
  13.     List(const List& L) : head(0)
  14.     {
  15.         for ( const Node* i = L.begin(); i!= L.end(); i=i->next )
  16.             push_front(i->data);
  17.         reverse();
  18.     }
  19.  
  20.     void reverse()
  21.     {
  22.         Node* p = 0; Node* i = begin(); Node* n;
  23.         while (i)
  24.         {
  25.             n = i->next;
  26.             i->next = p;
  27.             p = i; i = n;
  28.         }
  29.         head = p;
  30.     }
  31.  
  32.     void swap(List& x)
  33.     {
  34.         Node* tmp = head; head = x.head; x.head = tmp;
  35.     }
  36.  
  37.     List& operator=(const List& x)
  38.     {
  39.         List tmp(x);
  40.         swap(tmp);
  41.         return *this;
  42.     }
  43.  
  44.     ~List() { clear(); }
  45.     void clear() { while (!empty()) pop_front(); }
  46.  
  47.     bool empty() { return ! head; }
  48.  
  49.     void push_front(const int& x) {
  50.         Node* tmp = new Node(x,head); head = tmp;
  51.     }
  52.  
  53.     void pop_front() {
  54.         if (head) { Node* tmp = head; head=head->next; delete tmp; }
  55.     }
  56.  
  57.     void insert_after(Node* x, const int& data)
  58.     {
  59.         Node* tmp = new Node(data, x->next);
  60.         x->next = tmp;
  61.     }
  62.  
  63.     void erase_after(Node* x)
  64.     {
  65.         Node* tmp = x->next;
  66.         if (tmp)
  67.         {
  68.             x->next = x->next->next;
  69.             delete tmp;
  70.         }
  71.     }
  72.  
  73.  
  74.     int& front() { return head->data; }
  75.     const int& front() const { return head->data; }
  76.  
  77.     Node* begin() { return head; }
  78.     Node* end() { return 0; }
  79.  
  80.     const Node* begin() const { return head; }
  81.     const Node* end() const { return 0; }
  82.  
  83. private:
  84.     Node* head;
  85. };
  86.  
  87. #include <iostream>
  88. using namespace std;
  89.  
  90. int main()
  91. {
  92.     List X;
  93.     X.push_front(3);
  94.     X.push_front(2);
  95.     X.push_front(1);
  96.  
  97.     for (List::Node* it = X.begin(); it; it = it->next )
  98.         cout << it->data << endl;
  99.  
  100.     X.reverse();
  101.  
  102.     for (List::Node* it = X.begin(); it; it = it->next )
  103.         cout << it->data << endl;
  104.     return 0;
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement