-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path19.删除链表的倒数第-n-个结点.java
73 lines (59 loc) · 1.89 KB
/
19.删除链表的倒数第-n-个结点.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
* @lc app=leetcode.cn id=19 lang=java
*
* [19] 删除链表的倒数第 N 个结点
*/
// @lc code=start
import java.util.ArrayDeque;
import java.util.Deque;
/**
* Definition for singly-linked list.
* public 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 Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
return removeNthFromEndIteration(head, n);
}
/**
* 该题目的评论区提供了一种递归解法,但需要为 class 添加一个 index 属性记录节点下标。
*/
ListNode removeNthFromEndIteration(ListNode head, int n) {
// if need delete an item, having a dummy is helpful
ListNode dummy = new ListNode(-1, head);
// let probeTail go ahead n item, then probeTail and preTodelete go ahead
// simultaneously, when probeTail in tail, preTodelete.next is to be deleted
ListNode probeTail = dummy;
for (int i = 0; i < n; i++) {
probeTail = probeTail.next;
}
ListNode tmpPre = dummy;
while (probeTail.next != null) {
probeTail = probeTail.next;
tmpPre = tmpPre.next;
}
tmpPre.next = tmpPre.next.next;
return dummy.next;
}
ListNode removeNthFromEndStack(ListNode head, int n) {
Deque<ListNode> stack = new ArrayDeque<>();
ListNode dummy = new ListNode(-1, head);
ListNode cur = dummy;
while (cur != null) {
stack.offerLast(cur);
cur = cur.next;
}
for (int i = 0; i < n; i++) {
stack.pollLast();
}
ListNode preDel = stack.peekLast();
preDel.next = preDel.next.next;
return dummy.next;
}
}
// @lc code=end