61. 旋转链表
cpp
复制代码
/**
* 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) {
// 思路1:和数组一样做三次翻转
// 思路2:先连接尾节点和头节点成环,然后返回正数n-k+1个节点
if(head == nullptr) return nullptr;
int len = 1;
ListNode* p = head;
while(p->next){
len++;
p = p->next;
}
p->next = head;
k %= len;
// 移动n-k到目标节点的前一个节点
p = head;
for(int i = 0; i < len - k - 1; i++){
p = p->next;
}
head = p->next;
p->next = nullptr;
return head;
}
};
206. 反转链表
cpp
复制代码
/**
* 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* reverseList(ListNode* head) {
// 思路1:头插法
// 思路2:两两互换
ListNode *pre = nullptr, *cur = head, *temp = nullptr;
while(cur){
temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};