- 一开始想的是交换两个结点,比如12交换,再交换34,然后发现1无法指向4,所以正确的做法是操作三个结点,也引出虚拟头结点。
- 三步骤:(记不住)看图清晰点
当前结点指向2,2指向1,1指向3
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyhead=new ListNode(0);
dummyhead->next=head;
ListNode* tmp,*tmp1;//这样定义tmp1前要加*
ListNode* cur=dummyhead;
while(cur->next!=nullptr&&cur->next->next!=nullptr){
tmp=cur->next;
tmp1=cur->next->next->next;//易错
cur->next=cur->next->next;
cur->next->next=tmp;
cur->next->next->next=tmp1;//易错
cur=cur->next->next;
}
return dummyhead->next;
}
};
- 双指针,思想fast比slow快n步,然后同时移动,fast走到最后的时候,slow就是倒数第n个
- 注意细节,要删除倒数第n个,其实是要找到倒数第n-1个
lass Solution {//双指针法
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyhead=new ListNode(0);
dummyhead->next=head;
ListNode* slow=dummyhead,*fast=dummyhead;
for(int i=0;i<n;i++){
fast=fast->next;
}
fast=fast->next;//多走一步,为了让slow指向要删除的前一个结点
while(fast!=nullptr){
slow=slow->next;
fast=fast->next;
}
slow->next=slow->next->next;
return dummyhead->next;
}
};
- 关键是:两个链表末尾位置对齐,从那个起始点开始移动比较
- 链表相交不是val值相同,而是指针相等
/**
* 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) {
ListNode* cura=headA,*curb=headB;
int lena=0,lenb=0;
while(cura!=nullptr){
lena++;
cura=cura->next;
}
while(curb!=nullptr){
lenb++;
curb=curb->next;
}
cura=headA,curb=headB;
if(lenb>lena){
swap(lena,lenb);
swap(cura,curb);
}
int diff=lena-lenb;
for(int i=0;i<diff;i++)
cura=cura->next;
while(cura!=nullptr&&curb!=nullptr){
if(cura==curb)
return cura;
else {
cura=cura->next;
curb=curb->next;
}
}
return NULL;
}
};
- 判断是不是环,快慢指针,快每次走两步,慢每次走一步,看是否可相遇,是则为环
- 判断环的入口,一个从相遇的地方出发,一个从头结点出发,每次都走一步,相遇的地方是入口。(证明看代码随想录环形链表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* slow=head,*fast=head;
while(fast!=NULL&&fast->next!=NULL){//原因:因为fast要走两步
slow=slow->next;
fast=fast->next->next;
if(slow==fast){
ListNode* tmp=slow;
ListNode* tmp1=head;
while(tmp!=tmp1){
tmp=tmp->next;
tmp1=tmp1->next;
}
return tmp;
}
}
return NULL;
}
};