class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
ListNode* dummyHead = new ListNode();
dummyHead->next = head;
ListNode* fast = head;
ListNode* slow = dummyHead;
while (fast != nullptr && fast->next != nullptr) {
ListNode* temp = fast->next->next;
fast->next->next = slow->next;
slow->next = fast->next;
fast->next = temp;
slow = fast;
fast = fast->next;
}
head = dummyHead->next;
delete dummyHead;
return head;
}
};
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyHead = new ListNode();
dummyHead->next = head;
ListNode* fast = dummyHead;
head = fast;
while (n--) {
fast = fast->next;
}
while (fast->next != nullptr) {
fast = fast->next;
head = head->next;
}
fast = head->next;
head->next = head->next->next;
head = dummyHead->next;
delete dummyHead;
delete fast;
return head;
}
};
利用差值求相交节点
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int n = 0;
ListNode* curA = headA;
ListNode* curB = headB;
if (headA == nullptr || headB == nullptr) {
return nullptr;
}
while (curA->next != nullptr) {
n++;
curA = curA->next;
}
while (curB->next != nullptr) {
n--;
curB = curB->next;
}
if (curA != curB) {
return nullptr;
}
curA = n >= 0 ? headA : headB;
curB = curA == headA ? headB : headA;
n = abs(n);
while (n--) {
curA = curA->next;
}
while (curA != curB) {
curA = curA->next;
curB = curB->next;
}
return curA;
}
};
双指针
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA == nullptr || headB == nullptr) {
return nullptr;
}
ListNode* curA = headA;
ListNode* curB = headB;
while (curA != curB) {
curA = curA == nullptr ? headB : curA->next;
curB = curB == nullptr ? headA : curB->next;
}
return curA;
}
};
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head == nullptr || head->next == nullptr || head->next->next == nullptr) {
return nullptr;
}
ListNode* fast = head;
ListNode* slow = head;
do {
slow = slow->next;
fast = fast->next->next;
}while(fast != slow && fast->next != nullptr && fast->next->next != nullptr);
if (fast != slow) {
return nullptr;
}
fast = head;
while (fast != slow) {
fast = fast->next;
slow = slow->next;
}
return slow;
}
};