Java Basics - Doubly Linked List
Java Basics - Doubly Linked List
WIA1002/ WIB1002 :
Data Structures
1
Doubly Linked List
• A doubly-linked list (also called two-way 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(pointer), 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 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.
Pictorial View of Doubly Linked List
point to the next
• 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, 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.
Disadvantages
• Each node requires an extra pointer, requiring
more space
• The insertion or deletion of a node takes a bit
longer (more pointer operations)
The Node Class for Doubly Linked List
Each node consist of 2 pointers
next and prev also known as
‘variable of type object’
5
Class Definition for DoublyLinkedList
6
Doubly Linked List Insertion
• Insertion into a doubly-linked list has three
cases (same as singly linked list)
– Inserting a new node before the head
• addFirst(E element)
– Inserting a new node after the tail
• addLast(E element)
– Inserting a new node a the middle of the list
• add(int index, E element)
Inserting a Node at the Beginning
Inserting a Node at the Ending
Inserting a Node in the Middle
temp
temp
Inserting a Node in the Middle
11
//traverse & stop at requested index (in the case below
stop at index 2) if we want to add element at index 2.
temp.prev temp
next next next next
temp.prev temp
3.
prev prev prev prev
(temp.prev).next next
4.
Try to code!
Answer : Deleting an Intermediate Node
temp.next.prev
prev here is referring to the
prev variable of the next node
after index 2, namely, the node
at index 3
temp.prev.next
next here is referring to the
next variable of the prev node
before index 2, namely, the
node at index 1
Clear All Nodes in the List