一、删除链表的倒数第N个节点
1.题目
19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
2.思路
- 用多次扫描链表进行获取链表长度,移动到删除位置前。最重要的是防止空指针的操作!
- 双指针写法:分别定义快慢指针,快指针先走n+1步后,快慢指针一起移动,当快指针指到空指针时,慢指针达到了删除位置前一个位置。这个方法配合虚拟头结点更加容易理解。 原理如下:加上虚拟头结点后,链表长度为a+1,快指针走了n+1步后,还剩下a-n步到尾部空指针。因为n是倒着数,因此当慢指针走了a-n步后,到了删除节点的前一个位置。这个方法可以避免操作空指针,同时只需要遍历一遍。
3.代码
遍历多遍:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyhead = new ListNode(0);
dummyhead->next = head;
ListNode* temp1 = dummyhead;
int a = 0;//获得链表长度
while(temp1->next != nullptr){
a++;
temp1 = temp1->next;
}
ListNode* temp2 = dummyhead;
int b = a-n;
while(temp2->next != nullptr && b != 0){
b--;
temp2 = temp2->next;
}
if(temp2->next != nullptr){//防止操作空指针
ListNode* temp3 = temp2->next;
temp2->next = temp2->next->next;
delete temp3;
}
return dummyhead->next;
}
};
双指针法:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyhead = new ListNode(0);
dummyhead->next = head;
ListNode* fast = dummyhead;
ListNode* slow = dummyhead;
while(n-- && fast->next != nullptr){
fast = fast->next;
}
fast = fast->next;
//快指针走n+1步
while(fast != nullptr){
slow = slow->next;
fast = fast->next;
}
ListNode* temp = slow->next;
slow->next = slow->next->next;
delete temp;
return dummyhead->next;
}
};
二、链表相交
1.题目
面试题 02.07. 链表相交 - 力扣(LeetCode)
2.思路
求出两个链表的长度,并求出两个链表长度的差值,然后让curA移动到和curB 末尾对齐的位置。此时我们就可以比较curA和curB是否相同,如果不相同,同时向后移动curA和curB,如果遇到curA == curB,则找到交点。否则循环退出返回空指针。(注意判断哪个链表长)
3.代码
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* cur1 = headA;
ListNode* cur2 = headB;
int a = 0,b = 0;
while(cur1 != NULL){
a++;
cur1 = cur1->next;
}
while(cur2 != NULL){
b++;
cur2 = cur2->next;
}
int c = a-b;
cur1 = headA;
cur2 = headB;
if(c > 0){//A链表比B链表长
while(c--){
cur1 = cur1->next;
}
}
else{
while(-c){
cur2 = cur2->next;
c++;
}
}
while(cur1 != NULL){
if(cur1 == cur2) return cur1;
cur1 = cur1->next;
cur2 = cur2->next;
}
return NULL;
}
};