一、LeetCode24 两两交换链表中的节点
题目链接:LeetCode24
做题思路:
1、使用虚拟头结点,这样会方便很多,要不然每次针对头结点(没有前一个指针指向头结点),还要单独处理。接下来就是交换相邻两个元素了。
2、模拟过程如图所示:
代码如下所示:
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* DummyHead = new ListNode(0);
DummyHead->next = head;
ListNode* cur = DummyHead;
while(cur->next!=nullptr && cur->next->next!=nullptr)
{
ListNode* temp = cur->next;
ListNode* temp1 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = temp;
cur->next->next->next = temp1;
cur = cur->next->next;
}
return DummyHead->next;
}
};
二、LeetCode19 删除链表的倒数第N个节点
做题思路:
1、使用虚拟头结点,这样方便处理删除实际头结点的逻辑;
2、定义fast指针和slow指针,初始值为虚拟头结点:
3、fast首先走n + 1步 ,为什么是n+1呢,因为只有这样同时移动的时候slow才能指向删除节点的上一个节点(方便做删除操作),如图:
4、 fast和slow同时移动,直到fast指向末尾,如题:
5、删除slow指向的下一个节点,如图:
代码如下所示:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* DummyHead = new ListNode(0);
DummyHead -> next = head;
ListNode* FastIndex = DummyHead;
ListNode* SlowIndex = DummyHead;
n++;
while(n-- && FastIndex != nullptr)
{
FastIndex = FastIndex->next;
}
//FastIndex = FastIndex->next;
while(FastIndex != nullptr)
{
FastIndex = FastIndex->next;
SlowIndex = SlowIndex->next;
}
SlowIndex -> next = SlowIndex -> next -> next;
return DummyHead->next;
}
};