Week 5: Doubly Linked List Qazi Haseeb Yousaf Dept of CS Bahria University , Islamabad 1 Data structures and algorithms
Introduction The singly linked list contains only one pointer field i.e. every node holds an address of the next node. The singly linked list is uni -directional i.e. we can only move from one node to its successor. Doubly linked list : Each node has two pointers, next and previous Each node has one pointer to its successor (NULL if there is none) and one pointer to its predecessor (NULL if there is none). 2
Introduction 3 17 22 34 26 9 head data next prev successor predecessor
Introduction Linked list class Node { int data; Node* next; }; Doubly linked list class Node { Node * prev ; int data; Node *next; }; 4
7 Class implementation class node { public: int data; node *next; node * prev ; }; class DoublyList { public: node *head; DoublyList (){head = 0;} void add_end ( int value); void add_begin ( int value); void add_after ( int value, int newVal ); void delete_element ( int value); void display_dlist (); void traverse_forward (); void traverse_backward (); };
8 void DoublyList :: add_begin ( int value){ node *temp; temp = new node; temp-> prev = NULL; temp->next = NULL; temp->data = value; // If list has no elements if (head == NULL) { head = temp; } // List has element(s) temp->next = head; head-> prev = temp; head = temp; }
9 void DoublyList :: add_end ( int value){ node *s, *temp; temp = new node; temp->data = value; temp->next = NULL; temp-> prev = NULL; // If list has no elements if (head == NULL) { head = temp; } // List already has element(s) else { s = head; while (s->next != NULL) s = s->next; s->next = temp; temp-> prev = s; } }
10 void DoublyList :: add_after ( int value, int position){ // List is Empty if (head == NULL) { cout <<“List is empty”<< endl ; return; } node *q=head; int i ; //Take the pointer to desired index for (i = 1;i < position;i++) { q = q->next; if (q == NULL) { cout <<"There are less than "; cout <<position<<" elements."<< endl ; return; } } //Create a new node node * tmp = new node; tmp ->data = value;
11 //If inserting at the end if (q->next == NULL) { q->next = tmp ; tmp ->next = NULL; tmp -> prev = q; } //Insertion at an arbitrary node else { tmp ->next = q->next; tmp -> prev = q; tmp ->next-> prev = tmp ; q->next = tmp ; } }
12 void DoublyList :: delete_element ( int value){ Node *p=head; while (p!=NULL && p->data != value){ p = p->next; } if (p == NULL){ cout << "ERROR: Value sought not found."; return; } if (p-> prev == NULL) { //First Node to be deleted head = head->next; head-> prev = NULL; delete p; return; }
13 //Last node to be deleted if(p->next==NULL){ p-> prev ->next=NULL; delete p; return; } //Node in between other nodes to be deleted p-> prev ->next = p->next; p->next-> prev = p-> prev ; delete p; }