29 Nov 2013

Linked List: Deleted Node with given pointer

Problem Statement:
         Given a pointer of a Singly Linked List, delete the node pointed by the given Pointer.

Given Linked List with given Pointer pointing to "2"

Fig: Linked List with given pointer at 2

Solution: 

 Here the trick is copy the content of the next node that is "3" here to the given node ("2" here)
and delete the next node.



1
2
3
4
5
public void deleteNode(Node current){
  Node nextNode = current.next;
  current.data=nextNode.data ;
  current.next = nextNode.next;
 }

The Node structure of Linked List



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
/**
 * Linked List Node
 * @author Prateek
 */
class Node {

 public int data;
 public Node next;
 
 public Node(int data){
  this.data=data;
 }
 
 public String toString(){
  return ""+data;
 }
}

Note: This logic is not applicable for the last node in the Linked List.

Please post your comment and suggestions.
Happy Coding!! :)

1 comment:

  1. Aw, this was an incredibly nice post. Taking the time and actual effort to make
    a superb article… but what can I say… I hesitate a lot and never
    seem to get anything done.

    Feel free to surf to my webpage; rent jet

    ReplyDelete