-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMain21.java
More file actions
49 lines (45 loc) · 1.21 KB
/
Main21.java
File metadata and controls
49 lines (45 loc) · 1.21 KB
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
42
43
44
45
46
47
48
49
package JZOfferTuJi;
import java.util.Deque;
import java.util.LinkedList;
public class Main21 {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
ListNode first = head;
ListNode second = dummy;
while (n-- > 0){
first = first.next;
}
while (first != null){
first = first.next;
second = second.next;
}
second.next = second.next.next;
ListNode ans = dummy.next;
return ans;
}
}
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Main21_1{
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
Deque<ListNode> stack = new LinkedList<>();
ListNode cur = dummy;
while (cur != null){
stack.push(cur);
cur = cur.next;
}
while (n-- > 0){
stack.pop();
}
ListNode prev = stack.peek();
prev.next = prev.next.next;
ListNode ans = dummy.next;
return ans;
}
}