SHARE
TWEET

Untitled

a guest Mar 3rd, 2014 954 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <cstddef>
  2. #include <iostream>
  3.  
  4. #define eol "\n"
  5. using namespace std;
  6.  
  7. class LinkedList{
  8.     // Struct inside the class LinkedList
  9.     // This is one node which is not needed by the caller. It is just
  10.     // for internal work.
  11.     struct Node {
  12.         int x;
  13.         Node *next;
  14.     };
  15.  
  16. // public member
  17. public:
  18.     // constructor
  19.     LinkedList(){
  20.         head = NULL; // set head to NULL
  21.         cur = NULL;
  22.     }
  23.  
  24.     // This prepends a new value at the beginning of the list
  25.     void addValue(int val){
  26.         Node *n = new Node();   // create new Node
  27.         n->x = val;             // set value
  28.         n->next = head;         // make the node point to the next node.
  29.                                 //  If the list is empty, this is NULL, so the end of the list --> OK
  30.         head = n;               // last but not least, make the head point at the new node.
  31.         if( cur == NULL)
  32.                 cur = head;
  33.     }
  34.  
  35.         void rewind(){
  36.                 cur = head;
  37.         }
  38.         void next(){
  39.                 if( cur != NULL )
  40.                         cur = cur->next;
  41.         }
  42.         int getValue(){
  43.                 if( cur != NULL )
  44.                         return cur->x;
  45.                 return 0; // really we should raise exception
  46.         }
  47.         int hasValue(){
  48.                 return ( cur != NULL ? true : false );
  49.         }
  50.  
  51. // private member
  52. private:
  53.     Node *head; // this is the private member variable. It is just a pointer to the first Node
  54.     Node *cur;
  55. };
  56.  
  57. int main() {
  58.     LinkedList list;
  59.  
  60.     list.addValue(5);
  61.     list.addValue(10);
  62.     list.addValue(20);
  63.         list.rewind();
  64.  
  65.         while( list.hasValue()){
  66.                 cout << "Value: " << list.getValue() << eol;
  67.                 list.next();
  68.         }
  69.         list.rewind();
  70.         while( list.hasValue()){
  71.                 cout << "Value: " << list.getValue() << eol;
  72.                 list.next();
  73.         }
  74.     return 0;
  75. }
RAW Paste Data
Top