Doubly Linked List Basics
excerpt: The topics covered are traverse and add nodes to a doubly linked list. tags: doubly-linked-list-traversal
In a doubly linked list, the nodes have links that point to both the next and previous nodes in the list. Sentinels for head and tail can make it easier to manipulate the list from either end. For example, you can add and remove nodes from either end in O(1) time.
Doubly Linked List
The node for a doubly linked list has previous and next links.
|
|
The class for double linked list has the traverse method.
|
|
The traverse method will print: 0,1,2.
Add a Node
The basic operations for manipulating doubly linked lists are similar to singly linked list. Except that we must do some extra work to manage the previous links.
|
|
The node class now has getters and setters for previous and nxt links. Implement insert
method to insert a node after a given node in the DoubleLinkedList class.
|
|
Any any point in time, we have to keep track of which links have been updated. The code:
|
|
will not work. The reason is the link after.nxt has already been updated to point to the new node. The fix is to use node.nxt.