2081 9

CSC211 ยท 2081 ยท 5 marks

What is the algorithm for node insertion and deletion from specified position from doubly linked list.

What is the algorithm for node insertion and deletion from specified position from doubly linked list. [5]

Data Structures and AlgorithmsChapter 5: ListsBasic operations in Linked List

Quick answer

In a doubly linked list, each node has three fields: prev, info, and next.

Node Insertion and Deletion at Specified Position in Doubly Linked List

Insertion at Specified Position in Doubly Linked List

Algorithm

Algorithm: Insert a node at a specified position in a doubly linked list
Input: Position (pos), Data (val)

Steps:

  1. Create a new node and set newnode->info = val
  2. If head = NULL, then:
    • Set newnode->next = NULL
    • Set newnode->prev = NULL
    • Set head = newnode
    • Exit
  3. If pos = 1 (insert at beginning), then:
    • Set newnode->next = head
    • Set newnode->prev = NULL
    • Set head->prev = newnode
    • Set head = newnode
    • Exit
  4. Else, traverse to the specified position:
    • Set temp = head
    • Set count = 1
    • While count < pos - 1 and temp != NULL:
      • temp = temp->next
      • count = count + 1
    • End While
  5. If temp = NULL, then print "Position out of range" and Exit
  6. Set newnode->next = temp->next
  7. Set newnode->prev = temp
  8. If temp->next != NULL, then:
    • Set temp->next->prev = newnode
  9. Set temp->next = newnode
  10. End

Deletion at Specified Position in Doubly Linked List

Algorithm

Algorithm: Delete a node from a specified position in a doubly linked list
Input: Position (pos)

Steps:

  1. If head = NULL, then print "Empty list" and Exit
  2. Set temp = head
  3. If pos = 1 (delete from beginning), then:
    • Set hold = head
    • Set head = head->next
    • If head != NULL, then set head->prev = NULL
    • Free (hold)
    • Exit
  4. Else, traverse to the specified position:
    • Set count = 1
    • While count < pos and temp != NULL:
      • temp = temp->next
      • count = count + 1
    • End While
  5. If temp = NULL, then print "Position out of range" and Exit
  6. Set hold = temp
  7. If temp->prev != NULL, then:
    • Set temp->prev->next = temp->next
  8. If temp->next != NULL, then:
    • Set temp->next->prev = temp->prev
  9. Free (hold)
  10. End

Diagram Illustration

Before Insertion at position 2:

[NULL|10|-->]  <-->  [-->|20|-->]  <-->  [-->|30|NULL]

After Inserting 15 at position 2:

[NULL|10|-->] <--> [-->|15|-->] <--> [-->|20|-->] <--> [-->|30|NULL]

Key Point: In a doubly linked list, both the next pointer of the previous node and the prev pointer of the next node must be updated during insertion and deletion to maintain bidirectional linkage.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.