Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit edbfe26

Browse files
add LeetCode 19. 删除链表的倒数第N个节点
1 parent e5e2754 commit edbfe26

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png)
2+
>仰望星空的人,不应该被嘲笑
3+
4+
## 题目描述
5+
6+
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
7+
8+
示例:
9+
10+
```cpp
11+
给定一个链表: 1->2->3->4->5, 和 n = 2.
12+
13+
当删除了倒数第二个节点后,链表变为 1->2->3->5.
14+
```
15+
16+
说明:
17+
18+
给定的 n 保证是有效的。
19+
20+
进阶:
21+
22+
你能尝试使用一趟扫描实现吗?
23+
24+
来源:力扣(LeetCode)
25+
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
26+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
27+
28+
29+
30+
## 解题思路
31+
32+
双指针,先让一个指针q走n 步,然后另一个指针p一起走,当第一个指针q走到尾的时候,此时p指针就指向了我们要删除的节点,进行删除即可。
33+
34+
```javascript
35+
/**
36+
* Definition for singly-linked list.
37+
* function ListNode(val) {
38+
* this.val = val;
39+
* this.next = null;
40+
* }
41+
*/
42+
/**
43+
* @param {ListNode} head
44+
* @param {number} n
45+
* @return {ListNode}
46+
*/
47+
var removeNthFromEnd = function(head, n) {
48+
let dummyHead = new ListNode();
49+
dummyHead.next = head;
50+
let p = dummyHead;
51+
let q = dummyHead;
52+
let k = n;
53+
while(k--) q = q.next; // 先让一个指针先走n步
54+
while(q.next){ // 一起走
55+
q = q.next;
56+
p = p.next;
57+
}
58+
p.next = p.next.next; // 找到删除节点,进行删除
59+
return dummyHead.next;
60+
};
61+
```
62+
63+
64+
65+
## 最后
66+
文章产出不易,还望各位小伙伴们支持一波!
67+
68+
往期精选:
69+
70+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
71+
72+
<a href="https://github.com/Chocolate1999/leetcode-javascript">leetcode-javascript:LeetCode 力扣的 JavaScript 解题仓库,前端刷题路线(思维导图)</a>
73+
74+
小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you!
75+
76+
77+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
78+
79+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
80+
81+
```javascript
82+
学如逆水行舟,不进则退
83+
```
84+
85+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /