今天是6.9,正值端午假期,没啥事把昨天的博客补一下吧,,
每道题的方法:
24. 两两交换链表中的节点 :临时节点的存储和节点的删除
题目一链接:24. 两两交换链表中的节点 - 力扣(LeetCode)
思路:
画图理解,通过应用存点和删点的操作,两两交换节点。
代码:
细节及难点:
细节二:通过画图可知每次循环中 cur -> next,cur -> next -> next -> next需要存储
最后输出dummyhead -> next,即输出表头,还要delete dummyhead,最后使它指向nullptr
题目二链接:19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
思路:利用双指针法定位倒数第n个节点的前一个节点,然后删除节点。
代码:
struct ListNode{
int val;
ListNode* next;
ListNode():val(0),next(nullptr),{}
};
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyhead = new ListNode(0);
//忘记写了:
dummyhead -> next = head;
ListNode* fast = dummyhead;
ListNode* slow = dummyhead;
int m = n + 1;//使得slow指针恰好落在要删除的节点的前一个节点
while(m --) {
fast = fast -> next;
}
while(fast != nullptr) {
fast = fast -> next;
slow = slow -> next;
}
slow -> next = slow -> next -> next;
ListNode* result = dummyhead -> next;
delete dummyhead;
return result;
}
};
难点:
题目三链接:面试题 02.07. 链表相交 - 力扣(LeetCode)
思路:通过两个cur指针(有一个需要提前移动)遍历两个链表来寻找两个单链表的第一个相同节点(指的是LinkedNode,而不是节点的值),然后输出节点即可。
代码:
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int n = 0;
int m = 0;
ListNode* cur1 = headA;
//计算n,m
while(cur1 != nullptr) {
n ++;
cur1 = cur1 -> next;
}
ListNode* cur2 = headB;
while(cur2 != nullptr) {
m ++;
cur2 = cur2 -> next;
}
cur1 = headA;
cur2 = headB;
//遗漏了交换操作,让n是较大值,让cur1指向长链表
if(n < m) {
swap(n,m);
swap(cur1,cur2);
}
int sub = n - m;
while(sub --) {
cur1 = cur1 -> next;
}
while(cur1 != nullptr) {
if(cur1 == cur2) {
return cur1;
}
cur1 = cur1 -> next;
cur2 = cur2 -> next;
}
return nullptr;
}
};
难点:
解释细节1:让cur1提前移动的目的是使得两个链表的末尾对齐,使得两个指针对应起来。
题目四链接:142. 环形链表 II - 力扣(LeetCode)
思路:通过判断fast和slow移动后会不会相遇来确定是否有环;在有环的情况下,利用数学公式的推导可得出结论:图中的X和Z是相等的,因为(n - 1)(y + z)表示fast指针多转了几圈,所以利用x=z来求入口节点。
附加图:
代码:
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast != nullptr && fast -> next != nullptr) { //可以从fast = fast -> next -> next;推出来
//每次让fast只比slow快一步,可以确保二者可以相遇
//需要先移动两个指针,在进行if()判断
fast = fast -> next -> next;
slow = slow -> next;
if(fast == slow) {如果有环那么两个指针会相遇
ListNode* index1 = fast;
ListNode* index2 = head;
while(index1 != index2) {
//每次让index1和index2以相同速度移动
index1 = index1 -> next;
index2 = index2 -> next;
}
//此题是返回节点,所以直接返回index2
return index2;
}
}
//如果没有环,即fast = nullptr
return nullptr;
}
};
难点:
解释细节1:如果fast == null,那么fast -> next 会报错;同理fast -> next 的条件
解释细节2:相对速度为1可以确保二者肯定会相遇
解释细节3:因为一开始fast和slow相等,所以不能把if()判断写前面不然会出错。
解释细节4:根据x = z,当速度相同的两个指针相遇时,此时指向的节点就是入口节点