package problems.geeks.linkedlist;
/**
* Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?
*
* http://www.geeksforgeeks.org/given-only-a-pointer-to-a-node-to-be-deleted-in-a-singly-linked-list-how-do-you-delete-it/
*
* Fast solution is to copy the data from the next node to the node to be deleted and delete the next node. Something like following.
*
* struct node *temp = node_ptr->next;
* node_ptr->data = temp->data;
* node_ptr->next = temp->next;
* free(temp);
*/
import java.util.*;
import adt.ListNode;
import adt.LinkedList;
public class Q002_Deleted_Node {
public static void main(String[] args) {
}
static void deleteNode(ListNode head, ListNode node) {
if (node == null) {
return;
}
// if node is head
if (node == head) {
head = head.next;
node = null;
return;
}
// if node's next is not null
// swap the node and next node
if (node.next != null) {
node.val = node.next.val;
node.next = node.next.next;
return;
}
// then we have to find the node from the head
ListNode curr = head;
while (curr.next != node) {
curr = curr.next;
}
// could not find the node from the list
if (curr == null) {
return;
}
// delete it
curr.next = curr.next.next;
}
}