题目描述:
题号:19
给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
解题思路:
思路一:双指针(快慢指针)
使用两个指针 fast 和 slow 同时对链表进行遍历,并且 fast 比 slow 超前 n 个节点。当 fast 遍历到链表的末尾时,slow 就恰好处于倒数第 n 个节点。
使用虚拟头节点的原因是 示例2 那样的边界条件需要特殊处理,否则会引发空指针错误
时间复杂度:O(N)
空间复杂度:O(1)
C++
// C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head == nullptr) {
return nullptr;
}
ListNode* dummyHead = new ListNode(99999, head);
ListNode *fast = dummyHead, *slow = dummyHead;
for(int i = 0; i < n; i++) {
fast = fast->next;
}
while(fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next;
}
ListNode *temp = slow->next;
slow->next = slow->next->next;
ListNode *newHead = dummyHead->next;
// 防止内存泄露
delete temp;
delete dummyHead;
return newHead;
}
};
go
// go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeNthFromEnd(head *ListNode, n int) *ListNode {
if head == nil {
return nil
}
dummyHead := &ListNode{99999, head}
fast, slow := dummyHead, dummyHead
for i := 0; i < n; i++ {
fast = fast.Next
}
for fast != nil && fast.Next != nil {
fast = fast.Next
slow = slow.Next
}
slow.Next = slow.Next.Next
return dummyHead.Next
}