SunGard Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
I only know Java, so here it is.
public class LinkedLists {
static class Node {
String key;
Node next;
}
public static void main(String[] args) {
System.out.println(findNthLast(createList("a"), 1).key);
System.out.println(findNthLast(createList("a b"), 2).key);
System.out.println(findNthLast(createList("a b c"), 2).key);
System.out.println(findNthLast(createList("a b c d"), 2).key);
System.out.println(findNthLast(createList("a b c d e"), 2).key);
System.out.println(findNthLast(createList("a b c d e f"), 2).key);
}
public static Node createList(String keys) {
String[] parts = keys.split("\\s+");
Node list = new Node();
Node node = list;
node.key = parts[0];
for (int i = 1; i < parts.length; i++) {
node.next = new Node();
node.next.key = parts[i];
node = node.next;
}
return list;
}
public static Node findNthLast(Node list, int n) {
int i = 1;
Node node = list;
Node nthLast = null;
while (node != null) {
if (i == n) {
nthLast = list;
}
if (i > n) {
nthLast = nthLast.next;
}
node = node.next;
i++;
}
return nthLast;
}
}
-use two pointers
- Sourabh September 12, 2011-move one of the pointers n positions
-now move both the pointers simultaneously till the second pointer get's null
-ur first pointer will point to nth last element