Created
June 24, 2014 01:01
-
-
Save chrislukkk/a8edbb93ccd07acbdf0b to your computer and use it in GitHub Desktop.
CareerCup_2.2 - Find element kth to last
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
package Chapter2; | |
public class KthToLast { | |
public static <T> Node<T> kthToLast(MyLinkedList<T> list, int k) { | |
if (list.head == null) | |
return null; | |
Node<T> fir = list.head; | |
for (int i = 1; i < k; i++) { | |
if (fir.next == null) | |
return null; | |
fir = fir.next; | |
} | |
// runner tech | |
Node<T> sec = list.head; | |
while (fir.next != null) { | |
fir = fir.next; | |
sec = sec.next; | |
} | |
return sec; | |
} | |
public static void main(String[] args) { | |
MyLinkedList<Integer> list = new MyLinkedList<>(new Integer[] { 1, 2, | |
3, 4, 5, 6, 7, 8, 9, 10 }); | |
for (int i = 1; i <= 11; i++) { | |
System.out.println(i + "'s to the last element is " + | |
(kthToLast(list, i) == null ? "null " : kthToLast(list, i).data)); | |
} | |
} | |
} |
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
package Chapter2; | |
//Singly Linked List | |
public class MyLinkedList<T> { | |
public Node<T> head; | |
public MyLinkedList(Node<T> h) { | |
head = h; | |
} | |
public MyLinkedList(T[] dataArray) { | |
if (dataArray == null || dataArray.length <= 0) | |
return; | |
head = new Node<>(dataArray[0], null); | |
Node<T> node = head; | |
for (int i = 1; i < dataArray.length; i++) { | |
node.next = new Node<T>(dataArray[i], null); | |
node = node.next; | |
} | |
} | |
public void print() { | |
Node<T> cur = head; | |
while (cur != null) { | |
System.out.print(cur.data); | |
if (cur.next != null) { | |
System.out.print(" -> "); | |
} | |
cur = cur.next; | |
} | |
System.out.println(); | |
} | |
} |
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
package Chapter2; | |
public class Node<T> { | |
public T data; | |
public Node<T> next; | |
public Node(T d, Node<T> n){ | |
data = d; | |
next = n; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment