Thursday, July 23, 2015

Delete Node in a Linked List


Problem : Delete a node in single list list, except the tail node. Given access to only that node(node to be deleted. )
Ex : 1 -> 2 -> 3-> 4. You are given access to node 3 with value 3. 
Result 1 -> 2-> -> 4.

Basic idea is to copy the value from the next node in to current and delete the next node.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class Solution {
    public void deleteNode(ListNode node) {
        if(node == null || node.next == null){
            return;
        }else{
                // copy the data of the next node in the current node
                // delete the next node.
                node.val = node.next.val;
                node.next = node.next.next;
            }
    }
}

No comments:

Post a Comment