Doubly Linked List

Read this in other languages: Русский, 简体中文, 日本語, Português 한국어

In computer science, a doubly linked list is a linked data structure that consists of a set of sequentially linked records called nodes. Each node contains two fields, called links, that are references to the previous and to the next node in the sequence of nodes. The beginning and ending nodes’ previous and next links, respectively, point to some kind of terminator, typically a sentinel node or null, to facilitate the traversal of the list. If there is only one sentinel node, then the list is circularly linked via the sentinel node. It can be conceptualized as two singly linked lists formed from the same data items, but in opposite sequential orders.

Doubly Linked List

The two node links allow traversal of the list in either direction. While adding or removing a node in a doubly linked list requires changing more links than the same operations on a singly linked list, the operations are simpler and potentially more efficient (for nodes other than first nodes) because there is no need to keep track of the previous node during traversal or no need to traverse the list to find the previous node, so that its link can be modified.

Pseudocode for Basic Operations

Insert

  1. Add(value)
  2. Pre: value is the value to add to the list
  3. Post: value has been placed at the tail of the list
  4. n node(value)
  5. if head = ø
  6. head n
  7. tail n
  8. else
  9. n.previous tail
  10. tail.next n
  11. tail n
  12. end if
  13. end Add

Delete

  1. Remove(head, value)
  2. Pre: head is the head node in the list
  3. value is the value to remove from the list
  4. Post: value is removed from the list, true; otherwise false
  5. if head = ø
  6. return false
  7. end if
  8. if value = head.value
  9. if head = tail
  10. head ø
  11. tail ø
  12. else
  13. head head.next
  14. head.previous ø
  15. end if
  16. return true
  17. end if
  18. n head.next
  19. while n != ø and value !== n.value
  20. n n.next
  21. end while
  22. if n = tail
  23. tail tail.previous
  24. tail.next ø
  25. return true
  26. else if n != ø
  27. n.previous.next n.next
  28. n.next.previous n.previous
  29. return true
  30. end if
  31. return false
  32. end Remove

Reverse Traversal

  1. ReverseTraversal(tail)
  2. Pre: tail is the node of the list to traverse
  3. Post: the list has been traversed in reverse order
  4. n tail
  5. while n != ø
  6. yield n.value
  7. n n.previous
  8. end while
  9. end Reverse Traversal

Complexities

Time Complexity

AccessSearchInsertionDeletion
O(n)O(n)O(1)O(n)

Space Complexity

O(n)

References