给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
/** * 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: //双指针 //重要的思路是双指针最后倒数第二个,第一个low指针肯定指到倒二的前一个,第二个fast指针最后在末尾空指针,这样他们直接差了两个节点,所以开始的时候要移动n+1 ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* dummyHead = new ListNode(0); dummyHead->next = head; ListNode* slow = dummyHead; ListNode* fast = dummyHead; while(n-- && fast != NULL) { fast = fast->next; } fast = fast->next; // fast再提前走一步,因为需要让slow指向删除节点的上一个节点 while (fast != NULL) { fast = fast->next; slow = slow->next; } slow->next = slow->next->next; // ListNode *tmp = slow->next; C++释放内存的逻辑 // slow->next = tmp->next; // delete nth; return dummyHead->next; } };
标签:slow,ListNode,19,fast,next,链表,dummyHead,倒数第 From: https://www.cnblogs.com/lihaoxiang/p/17140540.html