Java Reference
In-Depth Information
Display 15.22
Adding a Node to the Front of a Doubly Linked List
1. Existing list.
null
"coat"
"shoes"
"socks"
null
head
2. Create new TwoWayNode linked to “coat”
TwoWayNode newHead = new TwoWayNode(itemName, null, head) // itemName = "shirt"
null
"shirt"
null
"coat"
"shoes"
"socks"
null
newHead
head
3. Set backward link and set new head
head.previous = newHead;
head = newHead;
null
"shirt"
"coat"
"shoes"
"socks"
null
newHead
head
The process of inserting a new node into the doubly linked list is shown in Display 15.24 .
In this case, we will insert the new node in front of the iterator referenced by position .
Note that there are also special cases for the insert routine when inserting to the front
or adding to the end of the list. Only the general case of inserting between two existing
nodes is shown in Display 15.24 .
A complete example of a doubly linked list is shown in Display 15.25. The code in
Display 15.25 is modified from the code in Display 15.17. Use of the doubly linked
list is virtually identical to use of a singly linked list. Display 15.26 demonstrates
addition, deletion, and insertion into the doubly linked list.
 
Search WWH ::




Custom Search