Leetcode 24. 两两交换链表节点19. 删除链表的倒数第 N 个结点142. 环形链表 II
24. 两两交换链表节点
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* VHead = new ListNode(0); // 设置一个虚拟头结点
VHead->next = head; // 将虚拟头结点指向head,这样方面后面做删除操作
ListNode* cur = VHead;
while(cur->next != nullptr && cur->next->next != nullptr) {
ListNode* tmp = cur->next; // 记录临时节点tmp指向1
ListNode* tmp1 = cur->next->next->next; // 记录临时节点tmp1指向3
cur->next = cur->next->next; // 步骤一:cur指向2
cur->next->next = tmp; // 步骤二:2指向1
cur->next->next->next = tmp1; // 步骤三:1指向3
cur = cur->next->next; // cur移动两位,准备下一轮交换
}
return VHead->next;
}
};
19. 删除链表的倒数第 N 个结点
Link of remove-nth-node-from-end-of-list
核心思想是删除节点距离终点n个单位,那么快指针先走n+1个单位,然后快慢指针同步走直到快指针指向nullptr,次时慢指针指向被删除节点的前一节点,方便进行删除操作
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* VHead = new ListNode(0);
VHead->next = head;
ListNode* slow = VHead;
ListNode* fast = VHead;//设置头节点;且快慢节点指向头节点
while(n-- && fast != NULL) {
fast = fast->next;
}//快节点先走n步
fast = fast->next; // fast再提前走一步,因为需要让slow指向删除节点的上一个节点
while (fast != NULL) {
fast = fast->next;
slow = slow->next;
}//fast,slow同时走,直到fast走到最后节点的下一步
slow->next = slow->next->next;
// ListNode *tmp = slow->next; C++释放内存的逻辑
// slow->next = tmp->next;
// delete tmp;
return VHead->next;
}
};
142. 环形链表 II
tLink of Linked-list-cycle-ii
难度在于快指针一次走两步,慢指针一次走一步展开的数学计算
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {// 快慢指针相遇,令head结点和相遇结点为index1,2,同时查找直至相遇
ListNode* index1 = fast;
ListNode* index2 = head;
while (index1 != index2) {
index1 = index1->next;
index2 = index2->next;
}
return index1; // 返回环的入口,x = (n - 1) (y + z) + z
}
}
return NULL;
}
};