Algorithms: Two-way linked list

Simple implementation of Two-way linked list in C++

#include<iostream.h>

class ListNode {
  int item;

public:
  ListNode *prev;
  ListNode *next;
  int GetItem() { return item; }
  ListNode(int data = 0) {
    this->item = data;
  }
};

class List {
  ListNode *head;
  ListNode *tail;
  int count;

  public:
    List() {
      this->head = NULL;
      this->tail = NULL;
      this->count = 0;
    }

    void Add(int data) {
      ListNode *n = new ListNode(data);
      this->count++;

      if(this->head == NULL) {
        this->head = n;
        this->tail = n;
      } else {
        n->prev = tail;
        tail->next = n;
        tail = n;
      }      
    }

    void Print (int index) {
      if(index < 0 || index >= this->count) {
        cout << "Index '" << index << "' out of range\n";
      } else {
        ListNode *n = this->head;
        for(int i=0; i<index; i++) {
          n = n->next;
        }
        cout << "Value at index " << index << ": " << n->GetItem() << "\n";         
      }
    }    
};

int main (int argc, char* argv) {
  List list;
// Add some items  
  for(int i = 0; i<6; i++) {    
    list.Add(i);
  }
// Print output with some indexes out of range
  for(int i = -1; i<=6; i++) {    
    list.Print(i);
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *