以综合题707和易错题24、142为例
class MyLinkedList {
private:
struct ListNode {
int val;
ListNode* next;
ListNode(int _val = 0, ListNode* _next = nullptr)
: val(_val)
, next(_next)
{
}
};
ListNode* dummy;
int64_t size;
public:
MyLinkedList()
: dummy(new ListNode(-1, nullptr))
, size(0)
{
}
int get(int index)
{
if (index > (size - 1) || index < 0)
return -1;
ListNode *pre = dummy, *cur = dummy->next, *next;
auto cur_index = index - index;
while (cur) {
next = cur->next;
if (cur_index == index) {
return cur->val;
}
++cur_index;
pre = cur;
cur = next;
}
return -1;
}
void addAtHead(int val) {
return addAtIndex(0, val); }
void addAtTail(int val) {
return addAtIndex(size, val); }
void addAtIndex(int index, int val)
{
if (index > size || index < 0)
return;
if (0 == size) {
dummy->next = new ListNode(val);
++size;
return;
}
ListNode *pre = dummy, *cur = dummy->next, *next;
auto cur_index = index - index;
while (cur) {
next = cur->next;
if (cur_index == index) {
ListNode* temp = new ListNode(val, cur);
pre->next = temp;
++size;
break;
}
++cur_index;
pre = cur;
cur = next;
}
if (index == size) {
ListNode* temp = new ListNode(val, cur);
pre->next = temp;
++size;
}
return;
}
void deleteAtIndex(int index)
{
if (index > (size - 1) || index < 0)
return;
ListNode *pre = dummy, *cur = dummy->next, *next;
auto cur_index = index - index;
while (cur) {
next = cur->next;
if (cur_index == index) {
pre->next = next;
delete cur;
--size;
break;
}
++cur_index;
pre = cur;
cur = next;
}
return;
}
};
class Solution {
public:
ListNode* swapPairs(ListNode* head)
{
if (!head)
return head;
if (!(head->next))
return head;
ListNode dummy = ListNode(-1, head);
ListNode *pre = &dummy, *cur = head, *next, *next2;
while (cur && cur->next) {
next = cur->next;
next2 = next->next;
pre->next = next;
next->next = cur;
cur->next = next2;
pre = cur;
cur = next2;
}
return dummy.next;
}
};
class Solution {
public:
ListNode* detectCycle(ListNode* head)
{
if (!head)
return NULL;
if (!(head->next))
return NULL;
ListNode dummy = ListNode(-1, head);
ListNode *slow = head, *fast = head;
while (slow && fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
while (slow != head) {
slow = slow->next;
head = head->next;
}
return slow;
}
}
return NULL;
}
};