对链表的操作有了更深的认识。
心得:操作链表元素时,一定要考虑操作完之后还能否找到其next和prev,从而判断是否需要先把前后的节点用临时变量保存下来。
第一题、LeetCode 24 两两交换链表中的节点 https://leetcode.cn/problems/swap-nodes-in-pairs/
同样设置虚拟头节点来免于对每个头节点单独处理。
交换时的节点操作步骤如图:
在循环时要分别判断奇数节点数和偶数的区别,并注意要先判断cur-next而不是cur-next-next来避免出现空指针异常。
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){
//分别考虑了链表数量是奇数和偶数的情况
//这两个不能交换否则会空指针异常,因为cur->next为空则其next就会报错
ListNode* tmp1 = cur->next; //保存cur后一位
ListNode* tmp3 = cur->next->next->next;//保存cur后第三位
cur->next = cur->next->next;
cur->next->next = tmp1;
tmp1->next = tmp3;
cur = cur->next->next;
}
return dummyhead->next;//因为不是一开始的head了
}
};
注意要保存上面示意图中节点1和3,避免2被操作后找不到1和3。
第二题、LeetCode 19.删除倒数第n个节点https://leetcode.cn/problems/remove-nth-node-from-end-of-list/
同样使用快慢指针的方法,快指针和慢指针中间中间间隔需要的长度即可。
先让快指针走n+1步,因为需要让慢指针停在需删除节点的前一个节点。
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyhead = new ListNode(0);
dummyhead->next = head;
ListNode* fast = dummyhead;
ListNode* slow = dummyhead;//设置快慢指针
n = n + 1;//让fast多往前走一步,使得slow停在需要删除的前一个节点
while(n-- && fast != NULL){ //fast先走
fast = fast->next;
}
while(fast != NULL){
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dummyhead->next;
}
};
第三题、面试02.07,LeetCode142 https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/
找到相交链表的相交点,除了遍历套着遍历,可以想象为找到两个链表的长度,然后相减得到差值。将然后让curA移动到,和curB 末尾对齐的位置,如图:
这样,就可以一起遍历curA和curB,不用循环套循环。
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
// ListNode* curA = headA;
// ListNode* curB = headB;
// while(curB != NULL){
// while(curA != NULL){
// if(curA->val == curB->val){
// break;
// return curA;
// }
// curA = curA->next;
// curA = headA;
// }
// curB = curB->next;
// }
// return NULL;
ListNode* curA = headA;
ListNode* curB = headB;
int lenA = 0, lenB = 0;//注意不能是int lenA, lenB = 0
while(curA != NULL){
lenA++;
curA = curA->next;
}
while(curB != NULL){
lenB++;
curB = curB->next;
}
curA = headA;
curB = headB;
if(lenA < lenB){ //确保lenA和curA是更长的那条
swap(lenA, lenB);
swap(curA, curB);
}
int gap = lenA - lenB;
while(gap--){
curA = curA->next;
}
while(curA != NULL){
if(curA == curB){
return curA;
}
curA = curA->next;
curB = curB->next;
}
return NULL;
}
};
第四题、LeetCode142:环形链表的入环第一个节点 https://leetcode.cn/problems/linked-list-cycle-ii/
快慢指针得思路在于想明白:快慢指针在环中相遇时,相遇点的位置之于入环口节点的距离,以及头节点到入环口距离的关系。
不论n等于几,在相遇点设置一个index1和头结点的index2同时往后走,一定会在入环第一个节点相遇。
代码:
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast != NULL && fast->next != NULL){
fast = 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;
}
};