24.两两交换链表中的结点
cur要指向的是两两交换指针的前一个链表,在while循环的条件cur->next=NULL一定要写在前面,如果在第一个指针就为空的话把cur->next->next=NULL放前面会空指针异常。
题目链接https://leetcode.cn/problems/swap-nodes-in-pairs/description/
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 *tmp=cur->next;//保存1
ListNode *tmp1=cur->next->next->next;//保存3
cur->next=cur->next->next;//cur指向2
cur->next->next=tmp;//2指向1
tmp->next=tmp1;//1指向3
cur=cur->next->next;//cur往后两位
}
return dummyhead->next;
}
};
当cur指向2的时候cur原来那条线就断了无法访问到1和3了所以要先保存下来
19.删除链表中的倒数第N个节点
题目链接https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/
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!=NULL){
fast=fast->next;
}
while(fast!=NULL){
fast=fast->next;
slow=slow->next;
}
ListNode* tmp=slow->next;
slow->next=tmp->next;
delete tmp;
return dummyhead->next;
}
};
哇,感觉这道题特别妙,要让快指针先走n+1步,这样让慢指针指向要删的那个结点的前一个,让慢指针前一个指向后一个把中间那个指针删掉就行了,就特别!!妙!!
while(n--&&fast->next!=NULL){
fast=fast->next;
}
最开始循环里面是这么写的就一直报错,循环里面是判断fast!=NULL,因为当fast指向空指针的时候fast->next就空指针异常了。
2.07链表相交
题目链接https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/description/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* curA=headA;
ListNode* curB=headB;
int lenA,lenB;
lenA=lenB=0;
while(curA!=NULL){
curA=curA->next;
lenA++;
}
while(curB!=NULL){
curB=curB->next;
lenB++;
}
curA=headA;
curB=headB;
if(lenB>lenA){
swap(lenB,lenA);
swap(curB,curA);
}
int len=lenA-lenB;
while(len--){
curA=curA->next;
}
while(curA!=NULL){
if(curA==curB){
return curA;
}
curA=curA->next;
curB=curB->next;
}
return NULL;
}
};
在把curA和curB遍历完之后要记得把它赋值回去 然后再判断长度之后进行交换,因为要交换的是指向链表的头结点,所以要先赋值再进行交换
142.环形链表
题目链接https://leetcode.cn/problems/linked-list-cycle-ii/description/
慢指针在中间与快指针相遇
(x+y)*2=x+y+n(y+z) //慢指针的路程=快指针的路程
x+y=n(y+z)
x=n(y+z)-y
x=(n-1)(y+z)+z //当n=1的时候,x=z,当n!=1的时候,就是在相遇之后,快节点继续循环,与从头结点来的指针在环形入口点相遇。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast=head;
ListNode* slow=head;
while(fast!=NULL&&fast->next!=NULL){//确保Fast下一个不是空指针以免
fast=fast->next->next; //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;
}
};