Your Computer Science Resource

Reverse a Doubly Linked List

This question comes up often in undergraduate CS classes, specifically Data Structures and Algorithms: How do you reverse a doubly linked list? Let’s find out! :)

Instructions

Let list be a doubly linked list with a header head and a tail tail. Each record has 3 fields: llink, data, rlink, where the two links give the records to the left and right, respectively. Write a pseudo-code procedure to reverse the linked list. That is, the element which was leftmost is now rightmost, etc.

Pseudo-code

// Procedure ReverseList( LinkedList list ):
// Input:	LinkedList list
// Output:	LinkedList list such that the list is in the reverse order of the input list.

// Swap head and tail

temp = list.head; 	// Store head in temp
list.head = list.tail;	// Head is now the tail
list.tail = temp;	// Tail is now the head
current = list.head;	// Current node

while ( current != null ) {

	temp = current.llink;		// Store left link in temp
	current.llink = current.next;	// Store next node in left link
	current.rlink = temp;		// Store temp in right link
	current = next;			// Move to next node

}

return list;

Leave a Reply