algoritmauzmanı
TREN
3.2Doubly Linked List
Lesson 3.2.6

Traversing in both directions

In a singly linked list you can only move forward. In a doubly linked list every also knows the node before it, so you can the list in both directions. In this lesson you print the list first from start to end, then from end to start.

What you will learn
  • How the list is walked from start to end with the links
  • How you reach the last node and come back with the links
  • Why walking backward is expensive in a singly linked list and cheap in a doubly linked one
4 minTime O(n)Memory O(1)C · Java · Python

1Idea

Walking forward is the same as traversing a singly linked list. A called temp starts at . In each round it prints the value of the node it points to and moves on with the link. When temp becomes NULL the list is done.

To walk backward you first reach the last node: temp moves forward until the node whose field is NULL. Then the direction changes: each round prints the value and moves to the previous node with the link. The first node's field is NULL, so the loop ends there.

If the list is empty, both functions print only an empty line. That is why the condition of the first loop in the backward walk checks whether temp is NULL first. If the list keeps a pointer to the last node, the first loop is not needed; the backward walk starts straight from .

2Step by step

The drawing walks a list holding 12, 7 and 3 forward, then backward. Green nodes have already been printed in the current direction. At each step the matching line of code lights up.

NULLNULL12?0x1a407?0x1a903?0x1b20headtemp
  1. Start. points to 12. The first node's field and the last node's field are NULL.
  2. Forward walk: temp starts at and prints 12. Output: 12
  3. temp moves to 7 with the link and prints 7. Output: 12 7
  4. temp moves to 3 and prints 3. Output: 12 7 3
  5. The field of 3 is NULL, so temp becomes NULL and the loop ends. A newline is printed.
  6. Backward walk: temp starts at , moves forward to the last node, 3, whose field is NULL, and prints 3. Output: 3
  7. temp moves to 7 with the link and prints 7. Output: 3 7
  8. temp moves to 12 and prints 12. Output: 3 7 12. The field of 12 is NULL, so the loop ends on the next round.

struct Node {    int data;    struct Node* prev;    struct Node* next;}; void printForward(struct Node* head) {    struct Node* temp = head;    while (temp != NULL) {        printf("%d ", temp->data);        temp = temp->next;    }    printf("\n");} void printBackward(struct Node* head) {    struct Node* temp = head;    while (temp != NULL && temp->next != NULL)  // go to the last node        temp = temp->next;    while (temp != NULL) {        printf("%d ", temp->data);        temp = temp->prev;    }    printf("\n");}
class Node {    int data;    Node prev, next;    Node(int data) { this.data = data; }} void printForward(Node head) {    Node temp = head;    while (temp != null) {        System.out.print(temp.data + " ");        temp = temp.next;    }    System.out.println();} void printBackward(Node head) {    Node temp = head;    while (temp != null && temp.next != null)  // go to the last node        temp = temp.next;    while (temp != null) {        System.out.print(temp.data + " ");        temp = temp.prev;    }    System.out.println();}
class Node:    def __init__(self, data):        self.data = data        self.prev = None        self.next = None def print_forward(head):    temp = head    while temp is not None:        print(temp.data, end=" ")        temp = temp.next    print() def print_backward(head):    temp = head    while temp is not None and temp.next is not None:  # go to the last node        temp = temp.next    while temp is not None:        print(temp.data, end=" ")        temp = temp.prev    print()

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n)

The forward walk visits each node once. The backward walk first goes to the end, then comes back: about 2n steps, still linear.

Memory
O(1)

A single temp pointer is enough; no extra list or stack is used.

Printing a singly linked list in reverse needs either extra memory (a stack, recursion) or reversing the list. In a doubly linked list the links do it without extra memory.

4Common mistake

The most common mistake is reusing the forward loop's condition to find the last node:

while (temp != NULL)    temp = temp->next;// temp is now NULL: there is no node to go back from

This loop does not stop at the last node; it moves past it to NULL. NULL has no field, so the backward walk never starts; reading temp->prev crashes the program. To stop at the last node the condition must be temp->next != NULL.

5Try it

On the list 12 ⇄ 7 ⇄ 3, how many times does printBackward follow a next link to reach the last node?

Show the answer

The answer is B. It moves from 12 to 7 and from 7 to 3: two times. The field of 3 is NULL, so the first loop stops there. If the list kept a pointer, this walk would not be needed at all.

Why does the second loop of the backward walk stop after printing 12?

Show the answer

The answer is B. The first node's field is NULL. After 12 is printed, temp = temp->prev assigns NULL and the condition while (temp != NULL) becomes false. The loop never looks at .

Lessons you mark show up in the curriculum. This is kept on this device only.