2.5 两两交换链表中的节点
链接:文章;视频;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* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* cur = dummyHead;
while (cur->next != NULL && cur->next->next != NULL) {
// 顺序不能写错,否则空指针报错
ListNode* temp = cur->next;
ListNode* temp1 = cur->next->next->next;
// 一定要先用临时指针记录
cur->next = cur->next->next;
cur->next->next = temp;
cur->next->next->next = temp1;
// 移动cur指针,进入下次循环
cur = cur->next->next;
}
return dummyHead->next;
}
};
2.6 删除链表的倒数第N个节点
链接:文章;视频;19.删除链表的倒数第N个节点
双指针法:快指针比慢指针多走n步,直至快指针走到空,删除慢指针即可
/**
* 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* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* curSlow = dummyHead;
ListNode* curFast = dummyHead;
n = n + 1; // 删除节点时需指到慢指针的前一位
while (n-- && curFast != NULL) {
curFast = curFast->next;
}
while (curFast != NULL) {
curFast = curFast->next;
curSlow = curSlow->next;
}
curSlow->next = curSlow->next->next;
return dummyHead->next;
}
};
2.7 链表相交
链接:文章;面试题02.07.链表相交
解题思路:两个链表相交后的后续长度是相等的
/**
* 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;
int lenB = 0;
ListNode* curA = headA;
ListNode* curB = headB;
while (curA != NULL) {
lenA++;
curA = curA->next;
}
while (curB != NULL) {
lenB++;
curB = curB->next;
}
curA = headA;
curB = headB;
if (lenB > lenA) {
swap (lenA, lenB);
swap (curA, curB);
}
int len = lenA - lenB;
while (len--) {
curA = curA->next;
}
while (curA != NULL && curB != NULL) {
if (curA == curB) {
return curA;
}
curA = curA->next;
curB = curB->next;
}
return NULL;
}
};
注意:数值相同,不代表指针相同
2.8 环形链表II
链接:文章;视频;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* fast = head; // fast走2步
ListNode* slow = head; // slow走1步
// 如果fast和slow可以相遇,则有环
while (fast != NULL && fast->next != NULL) { // 注意此条件
fast = fast->next->next;
slow = slow->next;
if (fast == slow) { // 相遇了
ListNode* index1 = head; // 从头结点开始走
ListNode* index2 = fast; // 从相遇节点开始走
while (index1 != index2) {
index1 = index1->next;
index2 = index2->next;
}
return index1;
}
}
return NULL;
}
};