单个链表反转方法
https://www.cnblogs.com/byrhuangqiang/p/4311336.html
使用就地反转法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* fanzhuan(ListNode* pre, ListNode* las)
{
ListNode* lpre = pre->next;
ListNode* cur = lpre->next;
while (cur != las)
{
lpre->next = cur->next;//这个lpre是不变的
cur->next = pre->next;
pre->next = cur;
cur = lpre->next;
}
return lpre;
}
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* dummy = new ListNode(0);
ListNode* pre=dummy;
dummy->next = head;
ListNode* cur = head;
int t = 1;
while (cur != NULL)
{
if (t%k == 0)
{
pre = fanzhuan(pre, cur->next);
cur=pre->next;
}
else
cur = cur->next;
t++;
}
return dummy->next;
}
};
使用头结点插入法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(head==NULL)return NULL;
ListNode* cur = head;
int n = 0;
while(cur!=NULL){
n++;
cur=cur->next;
}
if(n<k)return head;
n=0;
cur = head;
ListNode* pre = NULL;
ListNode *next =NULL;
while(n<k&&cur!=NULL){
n++;
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
if(cur!=NULL)
head->next = reverseKGroup(cur,k);
return pre;
}
};