class Solution {
public:
//链表题很容易出现段错误,一定要注意判断是否为空
ListNode* swapPairs(ListNode* head) {
ListNode* dum = new ListNode(0);
dum->next = head;
ListNode* cur = dum;
while(cur->next != nullptr && cur->next->next != nullptr){
ListNode* tem = cur->next;
ListNode* tem1 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = tem;
cur->next->next->next = tem1;
cur = tem;
}
return dum->next;
}
};
19.删除链表的倒数第N个节点
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dum = new ListNode(0);
dum->next = head;
ListNode* fast = dum;
ListNode* slow = dum;
n++;//让慢指针停在被删除节点的前一个节点
while(n--){
fast = fast->next;
}
while(fast){
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dum->next;
}
};
面试题 02.07. 链表相交
class Solution {
public:
int calLenth(ListNode *head){
int res = 0;
while(head){
head = head->next;
res++;
}
return res;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* heA = headA;
ListNode* heB = headB;
//函数返回结果后,链表必须保持其原始结构,所以不能直接使用headA和headB
int a = calLenth(heA);
int b = calLenth(heB);
if(a > b){
int c= a - b;
heA = headA;
heB = headB;
while(c--){
heA = heA->next;
}
}else{
int c = b - a;
heA = headA;
heB = headB;
while(c--){
heB = heB->next;
}
}
while(heA != heB){//两个节点相等时退出循环
heA = heA->next;
heB = heB->next;
if(heA == nullptr || heB == nullptr) return nullptr;
//只要有一个为空就退出循环
}
return heA;
}
};