day4第二章 链表 part02
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyHead=new ListNode(0);
dummyHead->next=head;//虚拟头节点位置不能变,最终返回交换后链表的头节点
ListNode*cur=dummyHead;
while(cur->next!=nullptr&&cur->next->next!=nullptr){/*偶数序列两两交换,下一个为
空;奇数序列剩1个,再下一个为空*/
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->next->next;//cur要移到可以操作下两个未被交换节点位置
}
return dummyHead->next;
}
};
1.两两交换链表中的节点
题目:https://leetcode.cn/problems/swap-nodes-in-pairs/
解析:帮你把链表细节学清楚! | LeetCode:24. 两两交换链表中的节点_哔哩哔哩_bilibili 老师讲得真的很好
盲点:
-
不可以操作空指针,条件先判断cur->next不为空,再判断cur->next->next;
cur->next若为空指针,cur->next->next就相当于操作空指针
2.cur是定义好的 一开始 指向虚拟头节点的指针,虚拟头节点是定义好的节点,不可能为空
2.删除链表的倒数第N个节点
题目:https://leetcode.cn/problems/remove-nth-node-from-end-of-list/
题解:
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;//fast先走n+1步,slow就会少走一步,即刚好到被移除节点前一个位置
while(m&&fast!=nullptr){
fast=fast->next;
m--;
}
while(fast!=nullptr){
fast=fast->next;
slow=slow->next;
}
slow->next= slow->next->next ;
return dummyHead->next;
}
};
3.面试题 02.07. 链表相交
题目:https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/
题解:
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode*curA=headA;
ListNode*curB=headB;
int lenA=1;//分别定义再赋值!!
int lenB=1;
while(curA!=NULL){
curA=curA->next;
lenA++;
}
while(curB!=NULL){
curB=curB->next;
lenB++;
}
curA=headA;
curB=headB;
if(lenB>lenA){
swap(lenA,lenB);//两个链表原始结构没有改变,只是换了名字
swap(curA,curB);//规定较长的链表 永远对应lenA,curA;
}
int differ=lenA-lenB;
while(differ){
curA=curA->next;//作为在较长链表上操作的节点curA往后移动
differ--; //到剩余长度与lenB一致
}
while(curA!=NULL){
if(curA==curB){//节点相同
return curA;//return结束语句
}
curA=curA->next;
curB=curB->next;
}
return NULL;
}
};
盲点
1.本题不需要用到虚拟头节点;不用移动/删除头节点,不会丢失其位置。
2.节点相同是内存地址完全相同(数据域和指针域)
debug
1.分开定义变量
int lenA, lenB=1;//这里其实只初始化lenB的值,lenA没有初始化值;
改正:
int lenA=1;
int lenB=1;
int a,b=0 是将b初始化为0,a没有初始化值
int a=0,b=0; 是将a的初始值设为0,b的初始值也设为0
4.环形链表II
题目: https://leetcode.cn/problems/linked-list-cycle-ii/
题解
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode*fast=head;
ListNode*slow=head;
while(slow!=NULL&&fast!=NULL&&fast->next!=NULL){
slow=slow->next;
fast=fast->next->next;
if(slow==fast){
ListNode*index1=fast;//也可以==slow,此时正相遇
ListNode*index2=head;
while(index1!=index2){
index1=index1->next;
index2=index2->next;
}
return index2;
}
}
return NULL;//不满足执行while的条件,直接return NULL
}
};
盲点:
- 若链表有环,快慢指针一定会在环内相遇(套圈)