Docsity

Doubly linked list and its examples, Lecture notes of Data Structures and Algorithms

Partial preview of the text

Download Doubly linked list and its examples and more Lecture notes Data Structures and Algorithms in PDF only on Docsity!

Data Structures and Algorithms

LECTURE 05 – DOUBLY LINKED LIST

  • In singly linked list, nodes have the access to the successors (next pointer)
  • However there is no access to the predecessors
  • This means we can’t go backwards in the list. E.g.,
    • In case of deleteFromTail(), and deleteNode(int el) operations, we had to traverse through complete list (while loop) to find the predecessor of the node to be deleted.
  • Why?
    • To restore the links properly
  • Non-empty doubly linked list.
  • Empty Linked List

class Node { public : int Info ; Node * next , * prev ; Node ( int el , Node * n = NULL , Node * p = NULL ) { Info = el ; next = n ; prev = p ; } };

  • Before :
  • After :

void addToTail ( int );

void DoublyLinkedList :: addToTail ( int el ) { if ( tail != NULL ) // if list is not empty { tail = new Node ( el , NULL , tail ) ; tail - > prev - > next = tail ; } else // if list is empty head = tail = new Node ( el ) ; Size ++ ; }

int DoublyLinkedList :: deleteFromTail () { int el = tail - > Info ; if ( head == tail ) // if only one node in the list { delete head ; head = tail = NULL ; } else // if more than one node in the list { tail = tail - > prev ; delete tail - > next ; tail - > next = NULL ; } Size -- ; return el ; }

  • Before :
  • After :

void deleteNode( int );