-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathGetKthFromEnd.java
41 lines (37 loc) · 994 Bytes
/
GetKthFromEnd.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.Stack;
public class GetKthFromEnd {
public ListNode getKthFromEnd(ListNode head, int k) {
if (head == null){
return null;
}
ListNode leftP = head;
ListNode rightP = head;
for (int i = 0; i < k; i++) {
rightP = rightP.next;
}
while (rightP != null){
leftP = leftP.next;
rightP = rightP.next;
}
return leftP;
}
public ListNode ReverseList(ListNode head) {
if(head == null){
return null;
}
ListNode curr = head;
Stack<ListNode> stack = new Stack<ListNode>();
while(curr != null){
stack.push(curr);
curr = curr.next;
}
ListNode temp = new ListNode(-1);
ListNode p = temp;
while(!stack.isEmpty()){
ListNode node = stack.pop();
p.next = node;
p = p.next;
}
return temp.next;
}
}