Unit-5_Java
Unit-5_Java
}}
Insertion
► In a single linked list, the insertion
operation can be performed in three
ways. They are as follows...
1. Inserting At Beginning of the
list 2. Inserting At End of the list
3. InsertingAt Specific location in the list
Inserting At Beginning of the list
• Assignthe reference of the HEAD to the new node’s next field.
• Make the new node as the HEAD of the list.
• //Point the new node's next to head
• newNode.next = this.head;
• // Make the new node as head
• this.head = newNode;
Inserting At End of the list
• Traverse the list until we find the last node.
• The new node’s reference is assigned to the last node’s next field.
• Node cur = this.head; • // traverse to the end of the list
• while (cur.next != null) {
• cur = cur.next;
•}
• cur.next = newNode;
Inserting At Specific location in the list
• Traverse (position – 1) times or till the end of the list is reached and
maintain previous and current references.
• Assign the reference of the new node to the prev node’s next field. •
Assign the cur node’s reference to the new node’s next field.
► To delete the last element from the circular linked list, traverse till the
second last element and change the previous node’s next to the last
node’s next.