Skip to content

Instantly share code, notes, and snippets.

@jyhjuzi
Created June 27, 2014 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jyhjuzi/1c751226bdbb31ea3e78 to your computer and use it in GitHub Desktop.
Save jyhjuzi/1c751226bdbb31ea3e78 to your computer and use it in GitHub Desktop.
public class Q2_2 {
public static void main(String args[]) {
Node test = arrayToLinkedList(new int[] { 1, 2, 3, 4, 5, 6 });
System.out.println(getKthEle(test, 1).value);
}
public static Node getKthEle(Node root, int k) {
Node pointer1 = root;
Node pointer2 = root;
for (int i = k; i > 0; i--) {
if (pointer2 == null)
return null;
else
pointer2 = pointer2.next;
}
while (pointer2 != null) {
pointer1 = pointer1.next;
pointer2 = pointer2.next;
}
return pointer1;
}
private static Node arrayToLinkedList(int[] array) {
Node head = new Node(array[0]);
Node current = head;
for (int i = 1; i < array.length; i++) {
current.next = new Node(array[i]);
current = current.next;
}
return head;
}
}
class Node {
int value;
Node next;
Node(int x) {
value = x;
next = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment