今天的题目主要是对双指针和虚拟节点的灵活使用
24 两两交换链表中的节点
用虚拟头结点,这样会方便很多。本题链表操作就比较复杂了,建议大家先看视频,视频里我讲解了注意事项,为什么需要temp保存临时节点。
题目链接/文章讲解/视频讲解: 代码随想录
思路模拟如下:
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyhead=new ListNode(0);
dummyhead->next=head;
ListNode* temp=dummyhead;
while(temp->next!=nullptr&&temp->next->next!=nullptr){
ListNode* node1=temp->next;
ListNode* node2=temp->next->next;
temp->next=node2;
node1->next=node2->next;
node2->next=node1;
temp=node1;
}
return dummyhead->next;
}
};
19删除链表的倒数第N个节点
双指针的操作,要注意,删除第N个节点,那么我们当前遍历的指针一定要指向 第N个节点的前一个节点,建议先看视频。题目链接/文章讲解/视频讲解:代码随想录
设置快慢指针。让快指针领先n+1步,我觉得其中容易出错的地方就是在while中判断fast不为空,而不是fast->next不为空。
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyhead=new ListNode(0);
dummyhead->next=head;
ListNode* fast=dummyhead;
ListNode* slow=dummyhead;
n++;
while(n--&&fast!=nullptr){
fast=fast->next;
}
while(fast!=nullptr){
fast=fast->next;
slow=slow->next;
}
slow->next=slow->next->next;
return dummyhead->next;
}
};
面试题02.07. 链表相交
本题没有视频讲解,大家注意 数值相同,不代表指针相同。题目链接/文章讲解:代码随想录
这道题一个易错点就是curA和curB用完之后记得重新指向head,swap(curA,curB)其实是让curA指向的链表A首地址换成指向链表B的首地址,curB也同理。
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *curA=headA;
ListNode *curB=headB;
int lenA=0;
int lenB=0;
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 gap=lenA-lenB;
while(gap--){
curA =curA->next;
}
while(curA!=NULL){
if(curA==curB){
return curA;
}
curA=curA->next;
curB=curB->next;
}
return NULL;
}
};
142.环形链表II
算是链表比较有难度的题目,需要多花点时间理解 确定环和找环入口,建议先看视频。题目链接/文章讲解/视频讲解:代码随想录
一定建议看下b站视频,明白是什么时候相遇的 ,明白出口是怎么判断的。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *fast =head;
ListNode *slow =head;
while(fast!=NULL&&fast->next!=NULL){
fast=fast->next->next;
slow=slow->next;
if(fast==slow){
ListNode *index1=fast;
ListNode *index2=head;
while(index1!=index2){
index1=index1->next;
index2=index2->next;
}
return index1;
}
}
return NULL;
}
};
欢迎各位大佬在评论区指正!