Tuesday, March 22, 2016

Find Nth Element From Last of the LinkedList in Single Pass

package LinkedList;

public class NthLastElementFromLast {

Nod head;
int size;

NthLastElementFromLast()
{
head = null;
size = 0;
}

public static void main(String args[])
{
NthLastElementFromLast elementFromLast = new NthLastElementFromLast();
elementFromLast.add(1);
elementFromLast.add(2);
elementFromLast.add(3);
elementFromLast.add(4);
elementFromLast.add(5);
elementFromLast.display();
elementFromLast.findNthFromLast(3);
}

void add(int val)
{
size++;
if(head == null)
{
head = new Nod(val,null);
}
else
{
Nod temp = new Nod(val,head);
head = temp;
}
}

void display()
{
Nod temp = head;
while(temp != null)
{
System.out.println(temp.data);
temp = temp.link;
}
}

void findNthFromLast(int n)
{
if(n>size || n<0)
return;
Nod temp = head;
Nod temp1 = head;
for(int i=0;i<n;i++)
temp = temp.link;
while(temp != null)
{
temp = temp.link;
temp1 = temp1.link;
}
System.out.println(temp1.data);

}

}

class Nod {
int data;
Nod link;
Nod()
{
data =0;
link = null;
}
Nod(int data,Nod link)
{
this.data = data;
this.link = link;
}
}

No comments:

Post a Comment