mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2026-02-02 18:39:09 +08:00
Merge branch 'master' into fixlinkedlist19java
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
<p align="center">
|
||||
<a href="https://programmercarl.com/other/xunlianying.html" target="_blank">
|
||||
<a href="https://www.programmercarl.com/xunlian/xunlianying.html" target="_blank">
|
||||
<img src="../pics/训练营.png" width="1000"/>
|
||||
</a>
|
||||
<p align="center"><strong><a href="https://mp.weixin.qq.com/s/tqCxrMEU-ajQumL1i8im9A">参与本项目</a>,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!</strong></p>
|
||||
<p align="center"><strong><a href="./qita/join.md">参与本项目</a>,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们受益!</strong></p>
|
||||
|
||||
|
||||
|
||||
@@ -98,27 +98,32 @@ public:
|
||||
### Java:
|
||||
|
||||
```java
|
||||
public ListNode removeNthFromEnd(ListNode head, int n){
|
||||
ListNode dummyNode = new ListNode(0);
|
||||
dummyNode.next = head;
|
||||
class Solution {
|
||||
public ListNode removeNthFromEnd(ListNode head, int n) {
|
||||
//新建一个虚拟头节点指向head
|
||||
ListNode dummyNode = new ListNode(0);
|
||||
dummyNode.next = head;
|
||||
//快慢指针指向虚拟头节点
|
||||
ListNode fastIndex = dummyNode;
|
||||
ListNode slowIndex = dummyNode;
|
||||
|
||||
ListNode fastIndex = dummyNode;
|
||||
ListNode slowIndex = dummyNode;
|
||||
// 只要快慢指针相差 n 个结点即可
|
||||
for (int i = 0; i <= n; i++) {
|
||||
fastIndex = fastIndex.next;
|
||||
}
|
||||
while (fastIndex != null) {
|
||||
fastIndex = fastIndex.next;
|
||||
slowIndex = slowIndex.next;
|
||||
}
|
||||
|
||||
// 只要快慢指针相差 n 个结点即可
|
||||
for (int i = 0; i <= n ; i++){
|
||||
fastIndex = fastIndex.next;
|
||||
// 此时 slowIndex 的位置就是待删除元素的前一个位置。
|
||||
// 具体情况可自己画一个链表长度为 3 的图来模拟代码来理解
|
||||
// 检查 slowIndex.next 是否为 null,以避免空指针异常
|
||||
if (slowIndex.next != null) {
|
||||
slowIndex.next = slowIndex.next.next;
|
||||
}
|
||||
return dummyNode.next;
|
||||
}
|
||||
|
||||
while (fastIndex != null){
|
||||
fastIndex = fastIndex.next;
|
||||
slowIndex = slowIndex.next;
|
||||
}
|
||||
|
||||
//此时 slowIndex 的位置就是待删除元素的前一个位置。
|
||||
//具体情况可自己画一个链表长度为 3 的图来模拟代码来理解
|
||||
slowIndex.next = slowIndex.next.next;
|
||||
return dummyNode.next;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Reference in New Issue
Block a user