Skip to content
Laviyx Learn

Try

DS Lab · Experiment 2

Doubly linked list operations

CLinked listsJNTUH R22 · CS306PC

Aim

To write a menu-driven C program that uses functions to create a doubly linked list, insert a node at the beginning, at the end or at a given position, delete a node by position or by value, and traverse the list both forwards and backwards.

Algorithm

  1. Define a node with three fields: prev (pointer to the previous node), data and next (pointer to the next node). Keep a pointer head to the first node.
  2. Create: read n values and add each one at the end of the list.
  3. Insert at beginning: set new->next = head; if the list is not empty set head->prev = new; make new the head.
  4. Insert at end: walk to the last node, set last->next = new and new->prev = last.
  5. Insert at position p: walk to node p − 1 (call it temp). Link the new node between temp and temp->next, fixing all four pointers.
  6. Delete a node (found by position or by value): set node->prev->next = node->next (or move head if it is the first node) and node->next->prev = node->prev (if there is a next node). Free the node.
  7. Traverse forwards from head using next. Traverse backwards by going to the last node and following prev.
  8. Repeat the menu until the user chooses Exit, then free every node.

Program

C
#include <stdio.h>
#include <stdlib.h>

struct node {
    struct node *prev;
    int data;
    struct node *next;
};

struct node *create_node(int value) {
    struct node *newnode = malloc(sizeof(struct node));
    if (newnode == NULL) {
        printf("Memory not available\n");
        exit(1);
    }
    newnode->prev = NULL;
    newnode->data = value;
    newnode->next = NULL;
    return newnode;
}

int count_nodes(struct node *head) {
    int count = 0;
    for (; head != NULL; head = head->next) {
        count++;
    }
    return count;
}

void display_forward(struct node *head) {
    if (head == NULL) {
        printf("List is empty\n");
        return;
    }
    printf("Forward:  ");
    for (struct node *temp = head; temp != NULL; temp = temp->next) {
        printf("%d%s", temp->data, temp->next != NULL ? " <-> " : "\n");
    }
}

void display_backward(struct node *head) {
    if (head == NULL) {
        return;
    }
    struct node *temp = head;
    while (temp->next != NULL) {        /* go to the last node */
        temp = temp->next;
    }
    printf("Backward: ");
    for (; temp != NULL; temp = temp->prev) {
        printf("%d%s", temp->data, temp->prev != NULL ? " <-> " : "\n");
    }
}

struct node *insert_begin(struct node *head, int value) {
    struct node *newnode = create_node(value);
    newnode->next = head;
    if (head != NULL) {
        head->prev = newnode;
    }
    return newnode;
}

struct node *insert_end(struct node *head, int value) {
    struct node *newnode = create_node(value);
    if (head == NULL) {
        return newnode;
    }
    struct node *temp = head;
    while (temp->next != NULL) {
        temp = temp->next;
    }
    temp->next = newnode;
    newnode->prev = temp;
    return head;
}

struct node *insert_at(struct node *head, int value, int pos) {
    if (pos < 1 || pos > count_nodes(head) + 1) {
        printf("Invalid position\n");
        return head;
    }
    if (pos == 1) {
        return insert_begin(head, value);
    }
    struct node *temp = head;
    for (int i = 1; i < pos - 1; i++) {     /* stop at node pos-1 */
        temp = temp->next;
    }
    struct node *newnode = create_node(value);
    newnode->next = temp->next;
    newnode->prev = temp;
    if (temp->next != NULL) {
        temp->next->prev = newnode;
    }
    temp->next = newnode;
    return head;
}

/* Unlink node del from the list and free it. Returns the new head. */
struct node *remove_node(struct node *head, struct node *del) {
    if (del->prev != NULL) {
        del->prev->next = del->next;
    } else {
        head = del->next;                   /* deleting the first node */
    }
    if (del->next != NULL) {
        del->next->prev = del->prev;
    }
    printf("Deleted %d\n", del->data);
    free(del);
    return head;
}

struct node *delete_at(struct node *head, int pos) {
    if (pos < 1 || pos > count_nodes(head)) {
        printf("Invalid position\n");
        return head;
    }
    struct node *temp = head;
    for (int i = 1; i < pos; i++) {
        temp = temp->next;
    }
    return remove_node(head, temp);
}

struct node *delete_value(struct node *head, int value) {
    struct node *temp = head;
    while (temp != NULL && temp->data != value) {
        temp = temp->next;
    }
    if (temp == NULL) {
        printf("%d not found in the list\n", value);
        return head;
    }
    return remove_node(head, temp);
}

void free_list(struct node *head) {
    while (head != NULL) {
        struct node *temp = head;
        head = head->next;
        free(temp);
    }
}

int read_int(const char *prompt, int *x) {
    printf("%s", prompt);
    return scanf("%d", x) == 1;
}

struct node *create_list(struct node *head) {
    int n, value;
    free_list(head);                        /* start a fresh list */
    head = NULL;
    if (!read_int("Enter number of nodes: ", &n) || n < 1) {
        printf("Invalid number of nodes\n");
        return NULL;
    }
    printf("Enter %d values: ", n);
    for (int i = 0; i < n; i++) {
        if (scanf("%d", &value) != 1) {
            printf("Invalid input\n");
            break;
        }
        head = insert_end(head, value);
    }
    return head;
}

int main(void) {
    struct node *head = NULL;
    int choice, value, pos;

    printf("DOUBLY LINKED LIST\n");
    printf("1. Create list\n2. Insert at beginning\n3. Insert at end\n");
    printf("4. Insert at position\n5. Delete at position\n6. Delete by value\n");
    printf("7. Display forward and backward\n8. Exit\n");

    do {
        if (!read_int("\nEnter your choice: ", &choice)) {
            printf("Invalid input\n");
            break;
        }
        switch (choice) {
        case 1:
            head = create_list(head);
            display_forward(head);
            break;
        case 2:
            if (read_int("Enter value: ", &value)) {
                head = insert_begin(head, value);
                display_forward(head);
            }
            break;
        case 3:
            if (read_int("Enter value: ", &value)) {
                head = insert_end(head, value);
                display_forward(head);
            }
            break;
        case 4:
            if (read_int("Enter value: ", &value) && read_int("Enter position: ", &pos)) {
                head = insert_at(head, value, pos);
                display_forward(head);
            }
            break;
        case 5:
            if (head == NULL) {
                printf("List is empty, nothing to delete\n");
            } else if (read_int("Enter position: ", &pos)) {
                head = delete_at(head, pos);
                display_forward(head);
            }
            break;
        case 6:
            if (head == NULL) {
                printf("List is empty, nothing to delete\n");
            } else if (read_int("Enter value to delete: ", &value)) {
                head = delete_value(head, value);
                display_forward(head);
            }
            break;
        case 7:
            display_forward(head);
            display_backward(head);
            break;
        case 8:
            break;
        default:
            printf("Invalid choice\n");
        }
    } while (choice != 8);

    free_list(head);
    printf("All nodes freed. Exiting.\n");
    return 0;
}

Output

Output
DOUBLY LINKED LIST
1. Create list
2. Insert at beginning
3. Insert at end
4. Insert at position
5. Delete at position
6. Delete by value
7. Display forward and backward
8. Exit

Enter your choice: 6
List is empty, nothing to delete

Enter your choice: 1
Enter number of nodes: 3
Enter 3 values: 10 20 30
Forward:  10 <-> 20 <-> 30

Enter your choice: 2
Enter value: 5
Forward:  5 <-> 10 <-> 20 <-> 30

Enter your choice: 3
Enter value: 40
Forward:  5 <-> 10 <-> 20 <-> 30 <-> 40

Enter your choice: 4
Enter value: 25
Enter position: 4
Forward:  5 <-> 10 <-> 20 <-> 25 <-> 30 <-> 40

Enter your choice: 5
Enter position: 3
Deleted 20
Forward:  5 <-> 10 <-> 25 <-> 30 <-> 40

Enter your choice: 6
Enter value to delete: 5
Deleted 5
Forward:  10 <-> 25 <-> 30 <-> 40

Enter your choice: 6
Enter value to delete: 40
Deleted 40
Forward:  10 <-> 25 <-> 30

Enter your choice: 6
Enter value to delete: 77
77 not found in the list
Forward:  10 <-> 25 <-> 30

Enter your choice: 7
Forward:  10 <-> 25 <-> 30
Backward: 30 <-> 25 <-> 10

Enter your choice: 8
All nodes freed. Exiting.

Recorded by compiling and running this exact program. Typed input appears after each prompt.

How it works

Positions are counted from 1. The backward display is the real test of a doubly linked list: it follows only the prev pointers, so if any prev link was set wrongly during an insert or delete, the backward order would not be the exact reverse of the forward order.

Because each node knows the node before it, one function remove_node handles every deletion. A singly linked list has to keep track of the previous node separately while searching.

Common mistakes

  • Fixing only the next pointers. Every insert and delete must also set the prev pointer of the node after the change, otherwise backward traversal breaks.

  • Writing del->next->prev = del->prev; without checking that del->next is not NULL. Deleting the last node then crashes the program.

  • Forgetting to set head->prev = newnode when inserting at the beginning of a non-empty list.

  • Not moving head when the first node is deleted, which leaves head pointing to freed memory.

Viva questions

Try to answer each one aloud before you open it.

  • How is a doubly linked list different from a singly linked list?

    Each node has two pointers: next to the following node and prev to the previous one. So the list can be traversed in both directions.

  • What is the advantage of the extra prev pointer?

    Given a pointer to a node, we can delete it or insert before it in O(1) time, because we can reach the previous node directly. Backward traversal also becomes possible.

  • What is the disadvantage?

    Each node needs memory for one more pointer, and every insert and delete has more pointers to update, so there are more chances for mistakes.

  • How many pointers change when a node is inserted in the middle of a doubly linked list?

    Four: the new node's prev and next, the previous node's next, and the following node's prev.

  • Where are doubly linked lists used?

    In places that move both ways, such as the back and forward history of a browser, undo and redo lists, and music playlists with next and previous.

Learn the concepts

All Data Structures Lab experiments →