解题思路
一道非常简单的双指针题目,定义快慢指针以及一个pre指针,快指针每次走两个节点,慢指针走一个节点,pre指针每次都在慢指针的前一位,当快指针到达终点或者是终点的next(即刚好空),此时的slow就在中间,利用pre把slow所在的节点给做掉,代码如下:
代码
/**
* 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* deleteMiddle(ListNode* head) {
if(head->next == nullptr) {
return nullptr;
}
ListNode* slow = head;
ListNode* fast = head;
ListNode* pre = nullptr;
while(1) {
if(fast == nullptr || fast->next == nullptr) {
break;
}
pre = slow;
slow = slow->next;
fast = fast->next->next;
}
pre->next = slow->next;
slow->next = nullptr;
delete slow;
return head;
}
};