Linked List - Deletion(given position of the node)
Delete the node given position of the node to be deleted and head of the list
Sample input1: position = 0, 1->2->3->4
Sample output1: 2->3->4
Sample input2: position = 2, 1->2->3
Sample output2: 1->3
Solution:
1) If position is 0 (head node) then make the head to point to
head->next
2) If position is greater than one then find the current node to be deleted by traversing the list also store the reference of previous node.
3) Make previous->next to point to current->next.
Code:
Node Delete(Node head, int position) {
if(position == 0){
head = head.next;
return head;
}
Node current = head;
Node prev=head;
for(int i=1; i<=position; i++){
prev = current;
current = current.next;
}
//if the position is greater than the list size
if(current == null) return head;
prev.next = current.next;
return head;
}
Illustration:
Delete position = 3 in 1->2->3->4
If condition fails as the given position != 0
Create two references current and prev and initialize them to point to head
At i = 1

At i = 2

At i = 3

At i = 4 loop terminates since position 4 is not <= 3
prev.next = current.next

Sample input1: position = 0, 1->2->3->4
Sample output1: 2->3->4
Sample input2: position = 2, 1->2->3
Sample output2: 1->3
Solution:
1) If position is 0 (head node) then make the head to point to
head->next
2) If position is greater than one then find the current node to be deleted by traversing the list also store the reference of previous node.
3) Make previous->next to point to current->next.
Code:
Node Delete(Node head, int position) {
if(position == 0){
head = head.next;
return head;
}
Node current = head;
Node prev=head;
for(int i=1; i<=position; i++){
prev = current;
current = current.next;
}
//if the position is greater than the list size
if(current == null) return head;
prev.next = current.next;
return head;
}
Illustration:
Delete position = 3 in 1->2->3->4
If condition fails as the given position != 0
Create two references current and prev and initialize them to point to head
At i = 1

At i = 2

At i = 3

At i = 4 loop terminates since position 4 is not <= 3
prev.next = current.next


Comments
Post a Comment