Download presentation
Presentation is loading. Please wait.
1
Doubly linked lists
2
Doubly-Linked List … start
Given a pointer to a node in a doubly-linked list, we can remove the node in ( 1 ) time. This isn’t possible in a singly-linked list, since we must have a pointer to the node in front of the one we want to remove.
3
Doubly-Linked List … start template <class DataType>
struct DLNode { DataType info; DLNode<DataType> *next; DLNode<DataType> *back; }; Each node is made from a struct that looks something like this.
4
Doubly-Linked List start …
5
Doubly-Linked List start ptr …
6
Doubly-Linked List … start ptr ptr->back->next = ptr->next;
ptr->next->back = ptr->back; delete ptr;
7
Doubly-Linked List … start ptr ptr->back->next = ptr->next;
ptr->next->back = ptr->back; delete ptr;
8
Doubly-Linked List … start ptr ptr->back->next = ptr->next;
ptr->next->back = ptr->back; delete ptr;
9
Doubly-Linked List … start ptr ptr->back->next = ptr->next;
ptr->next->back = ptr->back; delete ptr;
10
Doubly-Linked List … start ptr ptr->back->next = ptr->next;
ptr->next->back = ptr->back; delete ptr;
11
Doubly-Linked List … start ptr ptr->back->next = ptr->next;
ptr->next->back = ptr->back; delete ptr;
12
Doubly-Linked List … start ptr ptr->back->next = ptr->next;
ptr->next->back = ptr->back; delete ptr;
13
Implementation In the following implementation, names of the operations differ slightly from LinkedList (the single link version) Moreover, there is no getFirst or getNext. Instead, iteration is implemented as follows: L->First(); //sets the current position to the first item while(!L->AtEnd()) { cout << L->Item() << "\n"; //Item returns the list item at curr. pos L->Next(); //Next moves the curr. pos forward }
14
Implementation: Header and Trailer Nodes
List_Head List_Tail … struct Node { Etype Element; Node* Next; Node* Back; //Constructor for Node Node(Etype E = 0, Node *N = NULL, Node *P = NULL) : Element(E), Next(N), Back(P) {} }; Node* List_Head; Node* List_Tail; Node* Current_Pos;
15
Implementation: Constr. creates head & tail
//Constructor DoublyLinkedList() { //Construct the header List_Head = new Node(); List_Tail = new Node(); List_Head->Next = List_Tail; List_Tail->Back = List_Head; Current_Pos = List_Head; length = 0; };
16
Implementation: other operations
bool IsEmpty() void Next() void Back() bool atEnd() bool atStart() void Insert(const Etype & X) void Remove() //remove at current position bool Find(const Etype & X) void Replace(const Etype & X) void First(), void Last()
17
The insert operation void Insert(const Etype & X) { length++;
Current_Pos P 2 1 void Insert(const Etype & X) { length++; // Insert X after the current position Node* P = new Node(X); //see constructor P->Back=Current_Pos; /*1*/ P->Next=Current_Pos->Next; /*2*/ Current_Pos->Next = P; /*3*/ if (P->Next != NULL) P->Next->Back = P; /*4*/ };
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.