-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0019. 删除链表的倒数第N个节点
59 lines (52 loc) · 1.57 KB
/
0019. 删除链表的倒数第N个节点
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
1019. 删除链表的倒数第N个节点
题目描述提示帮助提交记录社区讨论阅读解答
随机一题
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *h = new ListNode(0);
h->next = head; //这样就不用分情况了
ListNode *first = h, *second = h;
for(int i=0; i<=n; i++)
first = first->next;
while(first){
first = first->next;
second = second->next;
}
second->next = second->next->next; //结点second->next一定存在
return h->next;
/*
ListNode *tmp = head, *find = head;
int i = 0;
while(tmp){
tmp = tmp->next;
if(i <= n)
i++;
else
find = find->next;
}
if(i == n) head = head->next; //删除第一个结点
else if(n == 1) find->next = NULL; //删除最后一个节点
else
find->next = find->next->next; //删除中间的结点
return head;
*/
}
};