题目描述
有一个链表 head, 给定一个值 val, 按定长val 反转链表
input: 链表头 head, 定长 val
output: 反转后的链表头
example: 输入链表[0, 1, 2, 3, 4, 5, 6], 长度为2,则输出为 [1, 0, 3, 2, 5, 4, 6]
思路
每次反转,保存一下上次的尾节点即可
代码
#include<iostream>
#include<vector>
using namespace std;
/*
* 链表分段反转
* 输入 node* head, int key 段长
*/
struct node{
int val;
node* next;
node(int vv, node* nn= nullptr): val(vv), next(nn){}
};
node* ReverseByLength(node* head, int len){
if(!head || len<=1) return head;
node* dummy = new node(0);
node* ppre = dummy, *now = head;
ppre->next = now;
while(now && now->next){
node* real_tail = now;
node* pre = nullptr;
int i = 0;
while(i<len && now){
node* next = now->next;
now->next = pre;
pre = now;
now = next;
i++;
}
ppre->next = pre;
ppre = real_tail;
ppre->next = now;
}
return dummy->next;
}
node* init_list(){
node* head = new node(0);
node* pre = head;
for(int i=1; i<10; i++){
pre = pre->next = new node(i);
}
return head;
}
void print(node* head){
while(head) {
cout << head->val << " ";
head = head->next;
}
cout<<endl;
}
int main(){
node* head = init_list();
print(head);
head = ReverseByLength(head, 2);
print(head);
return 0;
}