Advertisement
Rapptz

Untitled

May 3rd, 2012
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. class List {
  4. private:
  5.     struct node {
  6.         int data;
  7.         node* link;
  8.     } *p;
  9. public:
  10.     List() { p= NULL; }
  11.     void append(int number) {
  12.         node* x;
  13.         node* y;
  14.  
  15.         if(p == NULL) {
  16.             p = new node;
  17.             p->data = number;
  18.             p->link = NULL;
  19.         }
  20.         else {
  21.             x = p;
  22.             while(x->link != NULL)
  23.                 x = x->link;
  24.             y = new node;
  25.             y->data = number;
  26.             y->link = NULL;
  27.             x->link = y;
  28.         }
  29.     }
  30.     void addfirst(int number) {
  31.         node* x;
  32.         x = new node;
  33.         x->data = number;
  34.         x->link = p;
  35.         p = x;
  36.     }
  37.     void addafter(int a, int number) {
  38.         node* x;
  39.         node* y;
  40.         int i;
  41.         for(i=0,x=p; i<a;i++) {
  42.             x = x->link;
  43.             if(x == NULL) {
  44.                 std::cout << "You need at least " << a << " elements.\n";
  45.                 return;
  46.             }
  47.         }
  48.         y = new node;
  49.         y->data = number;
  50.         y->link = x->link;
  51.         x->link = y;
  52.     }
  53.     void del(int number) {
  54.         node* x;
  55.         node* z;
  56.         x = p;
  57.         if (x->data == number) {
  58.             p = x->link;
  59.             delete x;
  60.             return;
  61.         }
  62.  
  63.         z = x;
  64.         while(x!=NULL) {
  65.             if (x->data == number) {
  66.                 z->link = x->link;
  67.                 delete x;
  68.                 return;
  69.             }
  70.             z = x;
  71.             x = x->link;
  72.         }
  73.         std::cout << "Element " << number << " not found.";
  74.     }
  75.     void display() {
  76.         node* x;
  77.         std::cout << "\n";
  78.         for(x = p; x != NULL; x = x->link)
  79.             std::cout << x->data << std::endl;
  80.     }
  81.     int count() {
  82.         node* x;
  83.         int counter = 0;
  84.         for(x=p; x != NULL; x = x->link)
  85.             counter++;
  86.  
  87.         return counter;
  88.     }
  89.     ~List() {
  90.         node* x;
  91.         if (p == NULL)
  92.             return;
  93.  
  94.         while( p != NULL) {
  95.             x = p->link;
  96.             delete p;
  97.             p = x;
  98.         }
  99.     }
  100. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement