mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Merge pull request #1704 from vanyongqi/master
Update 0019.删除链表的倒数第N个节点.md
This commit is contained in:
@ -364,6 +364,40 @@ impl Solution {
|
|||||||
dummy_head.next
|
dummy_head.next
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
C语言
|
||||||
|
```c
|
||||||
|
/**c语言单链表的定义
|
||||||
|
* Definition for singly-linked list.
|
||||||
|
* struct ListNode {
|
||||||
|
* int val;
|
||||||
|
* struct ListNode *next;
|
||||||
|
* };
|
||||||
|
*/
|
||||||
|
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
|
||||||
|
//定义虚拟头节点dummy 并初始化使其指向head
|
||||||
|
struct ListNode* dummy = malloc(sizeof(struct ListNode));
|
||||||
|
dummy->val = 0;
|
||||||
|
dummy->next = head;
|
||||||
|
//定义 fast slow 双指针
|
||||||
|
struct ListNode* fast = head;
|
||||||
|
struct ListNode* slow = dummy;
|
||||||
|
|
||||||
|
for (int i = 0; i < n; ++i) {
|
||||||
|
fast = fast->next;
|
||||||
|
}
|
||||||
|
while (fast) {
|
||||||
|
fast = fast->next;
|
||||||
|
slow = slow->next;
|
||||||
|
}
|
||||||
|
slow->next = slow->next->next;//删除倒数第n个节点
|
||||||
|
head = dummy->next;
|
||||||
|
free(dummy);//删除虚拟节点dummy
|
||||||
|
return head;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
|
Reference in New Issue
Block a user