哨兵节点的运用。实际上可以用快慢指针,一次遍历即可。
/**
* 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) {
int length = 0;
ListNode* curr = head;
//记录链表长度
while (curr) {
length++;
curr = curr->next;
}
//该算法处理不了长度为1的特殊情况 单独处理
if (length == 1) {
return nullptr;
}
// 哨兵节点 用于遍历+删除
int mid = length / 2;
ListNode* pre = new ListNode(0, head);
while (pre) {
if (mid == 0) {
pre->next = pre->next->next;
break;
} else {
pre = pre->next;
mid--;
}
}
return head;
}
};