- Swap Nodes in Pairs
https://leetcode.cn/problems/swap-nodes-in-pairs/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummy = new ListNode(0, head);
ListNode* copy =dummy;
while (dummy && dummy->next && dummy->next->next) {
ListNode* next = dummy->next;
ListNode* nextnext = dummy->next->next->next;
dummy->next = dummy->next->next;
dummy->next->next = next;
dummy->next->next->next = nextnext;
dummy = dummy->next->next;
}
return copy->next;
}
};
- Remove Nth Node From End of List
https://leetcode.cn/problems/remove-nth-node-from-end-of-list/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummy = new ListNode(0, head);
ListNode* fast = dummy;
ListNode* slow = dummy;
while (n >= 0 && fast) {
fast = fast->next;
n--;
}
while (fast) {
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dummy->next;
}
};
面试题 02.07. Intersection of Two Linked Lists LCCI
https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/
两个链表尾端对齐,然后让curA移动到和curB 末尾对齐的位置,两个链表同时向后移动,找到相同的两个节点。
class Solution {
public:
int getLen(ListNode* head) {
int len = 0;
while (head) {
head = head->next;
len++;
}
return len;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int lenA = getLen(headA);
int lenB = getLen(headB);
if (lenA < lenB) {
swap(headA, headB);
swap(lenA, lenB);
}
int gap = lenA - lenB;
while (gap && headA) {
headA = headA->next;
gap--;
}
while (headA && headB) {
if (headA == headB) {
return headA;
}
headA = headA->next;
headB = headB->next;
}
return NULL;
}
};
- Linked List Cycle II
https://leetcode.cn/problems/linked-list-cycle-ii/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* slow = head;
ListNode* fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
slow = head;
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}
return slow;
}
}
return NULL;
}
};