206. 反转链表
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(nullptr==head||head->next==nullptr)return head;
auto next=head->next;
ListNode* pre=nullptr;
auto cur=head;
while(cur)
{
next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
return pre;
}
};
要保存反转当前节点的next之后的指针域,防止结点指向修改导致的链表丢失
92. 反转链表 II
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
ListNode* dummy=new ListNode(0,head);
ListNode* p0=dummy;
for(int i=0;i<left-1;++i)
p0=p0->next;
ListNode* pre=nullptr, *cur=p0->next;
for(int i=0;i<right-left+1;++i)
{
ListNode* next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
p0->next->next=cur;
p0->next=pre;
return dummy->next;
}
};
25. K 个一组翻转链表
class Solution {
public:
// 翻转一个子链表,并且返回新的头与尾
pair<ListNode*, ListNode*> myReverse(ListNode* head, ListNode* tail) {
ListNode* prev = tail->next;
ListNode* p = head;
while (prev != tail) {
ListNode* nex = p->next;
p->next = prev;
prev = p;
p = nex;
}
return {tail, head};
}
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* hair = new ListNode(0);
hair->next = head;
ListNode* pre = hair;
while (head) {
ListNode* tail = pre;
// 查看剩余部分长度是否大于等于 k
for (int i = 0; i < k; ++i) {
tail = tail->next;
if (!tail) {
return hair->next;
}
}
ListNode* nex = tail->next;
// pair<ListNode*, ListNode*> result = myReverse(head, tail);
// head = result.first;
// tail = result.second;
// 这里是 C++17 的写法
tie(head, tail) = myReverse(head, tail);//前面绑定给后面
// 把子链表重新接回原链表
pre->next = head;
tail->next = nex;
pre = tail;
head = tail->next;
}
return hair->next;
}
};
876. 链表的中间结点
141. 环形链表
142. 环形链表 II
143. 重排链表
class Solution {
public:
void reorderList(ListNode* head) {
if(nullptr==head)
return;
auto mid=mid_node(head);//找到中间节点
auto l1=head;
auto l2=mid->next;//分成两表
mid->next=nullptr;
l2=reverse_list(l2);//对表2,进行反转
merge_list(l1,l2);//合并两表
}
ListNode* mid_node(ListNode* head){
auto fast=head,slow=head;
while(fast&&fast->next)
{
slow=slow->next;
fast=fast->next->next;
}
return slow;
}
ListNode* reverse_list(ListNode* head){
ListNode* pre=nullptr;
auto cur=head;
while(cur!=nullptr){
auto next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
return pre;
}
void merge_list(ListNode* l1,ListNode* l2){
while(l1!=nullptr&&l2!=nullptr){
auto next1=l1->next;
auto next2=l2->next;
l1->next=l2;
l1=next1;
l2->next=l1;
l2=next2;
}
}
};