目录
LeetCode206 反转链表
LeetCode92 反转链表II
LeetCode25 K个一组翻转链表
LeetCode206 反转链表
/**
* 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) {
ListNode* pre=nullptr;
ListNode* cur=head;
while(cur){
ListNode* nex=cur->next;
cur->next=pre;
pre=cur;
cur=nex;
}
return pre;
}
};
LeetCode92 反转链表II
/**
* 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* reverseBetween(ListNode* head, int left, int right) {
ListNode* dummy=new ListNode(0);
dummy->next=head;
ListNode* p=dummy;
for(int i=0;i<left-1;i++) p=p->next;
ListNode* cur=p->next;
ListNode* pre=nullptr;
for(int i=0;i<right-left+1;i++){
ListNode* nex=cur->next;
cur->next=pre;
pre=cur;
cur=nex;
}
p->next->next=cur;
p->next=pre;
return dummy->next;
}
};
LeetCode25 K个一组翻转链表
/**
* 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* reverseKGroup(ListNode* head, int k) {
int n=0;
for(ListNode* i=head;i;i=i->next) n++;
ListNode* dummy=new ListNode(0);
dummy->next=head;
ListNode* p=dummy;
ListNode* cur=head;
for(;n>=k;n-=k){
ListNode* pre=nullptr;
for(int i=0;i<k;i++){
ListNode* nex=cur->next;
cur->next=pre;
pre=cur;
cur=nex;
}
ListNode* ne=p->next;
p->next->next=cur;
p->next=pre;
p=ne;
}
return dummy->next;
}
};