24. 两两交换链表中的节点
思路:过程考虑清楚就行,想不清楚的化可以把涉及到的节点都保存一下,写得会轻松一点。
题解:
/**
* 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* swapPairs(ListNode* head) {
ListNode *dummy_head = new ListNode(0, head);
ListNode *cur = dummy_head;
while (cur->next != nullptr && cur->next->next != nullptr)
{
ListNode *tmp = cur -> next -> next;
cur -> next -> next = tmp -> next;
tmp -> next = cur -> next;
cur -> next = tmp;
cur = cur -> next -> next;
}
head = dummy_head -> next;
delete dummy_head;
return head;
}
};
19.删除链表的倒数第N个节点
思路:快慢指针,删除倒数第n个节点,就让快指针先走n步,然后慢指针才动。注意删除某个节点,我们需要的是其前一个节点的位置。所以用dummy_head会很方便。
题解:
/**
* 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* removeNthFromEnd(ListNode* head, int n) {
ListNode *dummy_head = new ListNode(0, head);
ListNode *fastnode = dummy_head;
ListNode *slownode = dummy_head;
while (n--)
fastnode = fastnode -> next;
while (fastnode->next != nullptr)
{
fastnode = fastnode -> next;
slownode = slownode -> next;
}
ListNode *tmp = slownode -> next;
slownode -> next = tmp -> next;
delete tmp;
head = dummy_head -> next;
delete dummy_head;
return head;
}
};
面试题 02.07. 链表相交
思路:同样是快慢指针,求出长短链表的长度差diff,让长链表上的快指针先走diff步,然后遍历比较即可。
题解:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int lenA{0}, lenB{0};
ListNode *curA{headA}, *curB{headB};
while (curA != nullptr)
{
curA = curA -> next;
++lenA;
}
while (curB != nullptr)
{
curB = curB -> next;
++lenB;
}
if (lenA < lenB)
{
swap(lenA, lenB);
swap(headA, headB);
}
int diff = lenA - lenB;
curA = headA;
curB = headB;
while(diff--)
curA = curA -> next;
while(curA != nullptr)
{
if (curA == curB)
return curA;
curA = curA -> next;
curB = curB -> next;
}
return nullptr;
}
};
142.环形链表II
思路:纯技巧加一点数学推理,自己推过应该就知道思路了。具体可以看环形链表。
题解:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *slownode{head}, *fastnode{head};
while (fastnode != nullptr && fastnode->next != nullptr)
{
fastnode = fastnode -> next -> next;
slownode = slownode -> next;
while (fastnode == slownode)
{
ListNode *curA{head};
ListNode *curB{slownode};
while (curA != curB)
{
curA = curA -> next;
curB = curB -> next;
}
return curA;
}
}
return nullptr;
}
};