题目讲解:以综合题707和易错题24、142为例 class MyLinkedList {struct ListNode {int val;ListNode* next;ListNode(int _val = 0, ListNode* _next = nullptr): val(_val), next(_next){}};private:ListNode* dummy;int size;public:MyLinkedList(): dummy(new ListNode()), size(0){}int get(int index){if (index >= size || index < 0)return -1;ListNode *cur = dummy, *next;int cur_index = 0;for (next = cur->next; cur && next; next = cur->next) {if (cur_index == index) {return next->val;}cur = cur->next;++cur_index;}return cur->val;}// 不要单独实现头插和尾插,统一用指定下标插入实现void addAtHead(int val) { addAtIndex(0, val); }void addAtTail(int val) { addAtIndex(size, val); }void addAtIndex(int index, int val){if (index > size)return;if (index < 0)index = 0;ListNode *cur = dummy, *next, *temp;int cur_index = 0;for (next = cur->next; cur; next = cur->next) {if (cur_index == index) {temp = new ListNode(val);temp->next = next;cur->next = temp;++size;break;}cur = cur->next;++cur_index;}}void deleteAtIndex(int index){if (index >= size)return;ListNode *cur = dummy, *next, *temp;int cur_index = 0;for (next = cur->next; cur && next; next = cur->next) {if (cur_index == index) {temp = next;cur->next = next->next;delete temp;--size;break;}cur = cur->next;++cur_index;}}
};
class Solution {
public:ListNode* swapPairs(ListNode* head){if (!head || !(head->next))return head;ListNode dummy = ListNode(-1, head);ListNode *pre = &dummy, *cur = dummy.next, *next, *next2;for (next = cur->next; cur && next; next = cur->next) {next2 = next->next;pre->next = next;cur->next = next2;next->next = cur;// 易错点:pre要先更新,并且pre=curpre = cur;cur = next2;// 因为cur=next2,跳过了next// 所以更新后的cur无效,则结束,否则next的有效性无法确保if (!cur)break;}return dummy.next;}
};
class Solution {
public:ListNode* detectCycle(ListNode* head){if (!head)return head;if (!(head->next))return head->next;ListNode *slow, *fast;// 易错点:快慢指针有效性判断for (slow = fast = head;slow->next && fast->next && fast->next->next;) {slow = slow->next;fast = fast->next->next;if (slow == fast) {for (; slow != head;) {slow = slow->next;head = head->next;}return head;}}return nullptr;}
};