The Linked List Data structure
[12][3][4][7][5][6][7][3][5][6]
head ----^ ^---- tail
Append at head
[5][12][3][4][7][5][6][7][3][5][6]
head ----^ ^---- prev head ^---- tail
New head’s next = prev head
public void insertAtHead(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
Append at tail
[12][3][4][7][5][6][7][3][5][6][8]
head ----^ prev tail ----^ ^---- tail
New tail’s next = null Prev tail’s next = new tail
public void insertAtTail(int data) {
Node newNode = new Node(data);
if(head == null){
head = newNode;
}else{
Node temp = head;
while(temp->next){
temp = temp->next;
}
temp->next = newNode;
}
}
public void insertAtTail(int data) {
Node newNode = new Node(data);
tail.next = newNode;
tail = newNode;
}
Delete by key
public void deleteNode(int key) {
Node temp = head, prev = null;
// If head node itself holds the key
if (temp != null && temp.data == key) {
head = temp.next;
return;
}
// Search for the key to be deleted
while (temp != null && temp.data != key) {
prev = temp;
temp = temp.next;
}
if (temp == null) return;
// Unlink the node from linked list
prev.next = temp.next;
}