文章内容是自己刷leetcode官方刷题攻略的一些经验与总结。
题目链接详见 leetcode刷题攻略
如果喜欢的话,别忘了点个赞哦 ^ _ ^
一.61旋转链表
1.题目描述
2.题目分析与解答
我们需要将链表中每个节点右移 k 位,但是 k 可能会比链表长度长,所以用 k 对链表长度 n 取模,即 k %= n。
然后使用双指针法找到新链表的头、尾位置,找到之后分别处理两段链表。
就拿示例一来说:1 2 3 4 5,我们找到的分割位置在 3 和 4 之间,即1 2 3 | 4 5,使用虚拟头节点,让其指向 4,让 3 的 next 指针指向空,让 5 的 next 指针指向 1。
C++ 代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
//首先记录链表的长度n,k = k % n; 防止重复运算
//然后使用双指针找到分割的节点位置
//处理两段链表
//k = k % n
if(!head) return nullptr;
if(k == 0) return head;
ListNode *cur = head;
int n = 0;
while(cur) {
n ++;
cur = cur->next;
}
k %= n;
//slow指针找到分割点的位置
ListNode *dummyHead = new ListNode(0, head);
ListNode *fast = dummyHead, *slow = dummyHead;
while(k >= 0) {
k --;
fast = fast->next;
}
while(fast) {
fast = fast->next;
slow = slow->next;
}
//处理两段链表
//1 2 3 | 4 5 slow指向3,fast指向4
fast = slow->next;
if(!fast) return head; //防止只有一个元素,下面的while报空指针错误
cur = fast;
while(cur->next) {
cur = cur->next;
}
cur->next = head;
slow->next = nullptr;
dummyHead->next = nullptr;
delete(dummyHead);
return fast;
}
};
二.24两两交换链表中的节点
1.题目描述
2.题目分析与解答
我以下图为例来分析:
我们先建立一个虚拟头指针,因为需要交换两两节点的位置,我们将节点一与节点二分别用 t1、t2 记录下来,依次更新 dummy -> 1 -> 2 -> 这三个指针。
如图所示,更新过程如下:
- cur -> next = t2
- t1 -> next = t2 -> next
- t2 -> next = t1
- cur = t1
至此一次更新完毕。
C++ 代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
//注意顺序,发现2,1,3或者2,3,1都可以
ListNode *dummyHead = new ListNode(0, head);
ListNode *cur = dummyHead;
while(cur->next && cur->next->next) {
ListNode *t1 = cur->next, *t2 = cur->next->next;
cur->next = t2;
t1->next = t2->next;
t2->next = t1;
cur = t1;
}
cur = dummyHead->next;
delete(dummyHead);
return cur;
}
};