Monday, January 25, 2016

Find Nth Node From End in likedList in Java




    Input    1--->2---->3-----4--->5------>6


find 4 position from  end...

public void findNthNodeFromEnd(ListNode head, int NthPosition){
ListNode p,q;
Hashtable<Integer, ListNode> table = new Hashtable<Integer, ListNode>();
int i = 1;
int length = 0;
for(p = head; (q = p.getNext())!= null; p =q){
/**
* here first I am getitng next node then adding to hash Table just to
* avoid adding the address of head Node
*/
p = p.getNext();
table.put(i, p);
i++;
length++;
}

//System.out.println("Hash table is:-"+table);
System.out.println(NthPosition+":-position form end is:-"+table.get((length-NthPosition)+1).getData());
}

No comments:

Post a Comment