一、24 两两交换链表中的节点:注意指向的顺序以及循环的条件
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *dummyHead=new ListNode(0);//没有给定值 一开始写的是空的 后续报错 等于空指针赋值吗
ListNode *cur=dummyHead;
ListNode *temp; //NO.1节点
ListNode *temp1;//NO.1下下个节点
dummyHead->next=head;
while(cur->next!=nullptr && cur->next->next!=nullptr){
temp=cur->next;//保留1的位置
temp1=cur->next->next->next;//保留3的位置
cur->next=cur->next->next;//dummyhead指向2
cur->next->next=temp;//2指向1
cur->next->next->next=temp1;//1指向3
cur=cur->next->next;//指针往后移动2位
}
return dummyHead->next;//为什么写return head会报错?
}
};
二、19 删除链表中倒数第n个节点:双指针法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *dummyHead= new ListNode(0);
ListNode *fast;
ListNode *slow;
ListNode *temp;
dummyHead->next=head;//这一步怎么能漏下!
fast=dummyHead;
slow=dummyHead;
n+=1;
while(n && fast!=nullptr ){ //循环n次
fast=fast->next;
n--;
}
while(fast!=nullptr){ //如果不让fast动就是死循环了啊
fast=fast->next;
slow=slow->next;
}
temp=slow->next;
slow->next=slow->next->next;//第一次没有两边写->next
delete temp;
return dummyHead->next;
}
};
三、面试题0207 链表相交:把cur移动到同一位置在进行一一比较
/**
* 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;
ListNode *curB=headB;
int lenA=0;
int 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 count=lenA-lenB;
while(count--){
curA=curA->next;
}
while(curA!=nullptr){
if(curA==curB){
return curA;
}
curA=curA->next;
curB=curB->next;
}
return NULL; //放在if的对立面else return NULL会报错
}
};