Reputation: 1829
I have been implementing this interview question in Java . A fairly simple problem with an additional constraint of size :
Find the Nth Node from the end of a Linked List where the size of the Linked List is unknown?
I am not concerned with the solution to this problem,because I have already figured that out.
Instead, I want to know whether my implementation maintains the coding conventions which experienced coders maintain while coding a problem related to Linked Lists and it's implementation?.Here is my implementation of the above problem:
import java.io.*;
class NthNodeFromEnd<AnyType>
{
private Node<AnyType> head;
private Node<AnyType> pointer;
private class Node<AnyType>
{
protected AnyType item;
protected Node<AnyType> next;
}
void push(AnyType item)
{
if(isEmpty())
{
head = new Node<AnyType>();
head.item = item;
head.next = null;
pointer = head;
}
else
{
Node<AnyType> newNode = new Node<AnyType>();
newNode.item = item;
newNode.next = null;
pointer.next = newNode;
pointer = pointer.next;
}
}
boolean isEmpty()
{
return head == null;
}
AnyType printNthLastNode(int n)
{
Node<AnyType> ptr1 = head;
Node<AnyType> ptr2 = head;
for(int i =0;i<n;i++)
{
ptr1 = ptr1.next;
}
while(ptr1!=null)
{
ptr1 = ptr1.next;
ptr2 = ptr2.next;
}
return ptr2.item;
}
public static void main(String args[])
{
NthNodeFromEnd<Integer> obj = new NthNodeFromEnd<Integer>();
obj.push(1);
obj.push(2);
obj.push(3);
obj.push(4);
obj.push(5);
obj.push(6);
obj.push(7);
System.out.println("The nth item is = "+obj.printNthLastNode(5));
}
}
P.S. - I am aware of the fact that there is an inbuilt implementation of Linked List in Java, but I don't want to use that.I want to know whether this implementation of the problem is good enough or is there a better way to tackle Linked List related problems?
Upvotes: 0
Views: 517
Reputation: 692121
Regarding the code conventions:
for(int i =0;i<n;i++)
should be for (int i = 0; i < n; i++)
printNthLastNode()
should print the nth last node, not return it. A method returning it should be named getNthLastNode()
or findNthLastNode()
. BTW, this method doesn't return a node, but a value stored in the list.printNthLastNode()
will fail with a NPE if the list is empty or not large enough. A better exception type should be used to signal this problem.java.io.*
, since it doesn't use any class from java.io. packages should generally not be imported. Classes should. String[] args
is more readable than String args[]
, and is more conventional.That said, the interviewer should see, with the code posted, that you understand how a linked list works and how pointers work, as well as generic types.
Upvotes: 1