-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem19.cpp
67 lines (63 loc) · 1.45 KB
/
problem19.cpp
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
/*
* @lc app=leetcode.cn id=19 lang=cpp
*
* [19] 删除链表的倒数第N个节点
*
* https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/description/
*
* algorithms
* Medium (37.95%)
* Likes: 720
* Dislikes: 0
* Total Accepted: 135.4K
* Total Submissions: 356.5K
* Testcase Example: '[1,2,3,4,5]\n2'
*
* 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
*
* 示例:
*
* 给定一个链表: 1->2->3->4->5, 和 n = 2.
*
* 当删除了倒数第二个节点后,链表变为 1->2->3->5.
*
*
* 说明:
*
* 给定的 n 保证是有效的。
*
* 进阶:
*
* 你能尝试使用一趟扫描实现吗?
*
*/
// @lc code=start
/**
* 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* dummy = new ListNode(0);
dummy->next = head;
ListNode* front = dummy;
ListNode* rear = front;
for(int i=0; i<n; i++) {
rear = rear->next;
}
while(rear->next!=NULL) {
front = front->next;
rear = rear->next;
}
ListNode* nthNodeFromEnd = front->next;
front->next = nthNodeFromEnd->next;
delete nthNodeFromEnd;
return dummy->next;
}
};
// @lc code=end