Created
June 27, 2014 18:41
-
-
Save jyhjuzi/1c751226bdbb31ea3e78 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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