链表分段反转

来源:互联网 发布:软件图标显示异常 编辑:程序博客网 时间:2024/05/19 17:58

链表翻转。给出一个链表和一个数k,比如链表1→2→3→4→5→6,k=2,则翻转后2→1→4→3→6→5,若k=3,翻转后3→2→1→6→5→4,若k=4,翻转后4→3→2→1→5→6,用程序实现


#include<stdio.h>#include<stdlib.h>#include<iostream>using namespace std;struct Node{int data;Node *next;};void reverse(Node *head,Node *end){if(head==NULL||end==NULL) return;Node *pre=NULL,*cur=head,*stop=end->next;while(cur!=stop){Node* nxt=cur->next;cur->next=pre;pre=cur;cur=nxt;}}Node* reverseAll(Node *head,int k){if(head==NULL||k<=0) return NULL;Node *cur=head;for(int i=0;i<k-1;i++){cur=cur->next;if(cur==NULL)    break;}if(cur==NULL) return head;Node* begin=cur->next,*end=begin;Node* pre=head;reverse(head,cur);while(begin!=NULL){for(int i=0;i<k-1;i++){end=end->next;if(end==NULL)    break;}if(end==NULL){pre->next=begin;break;}else{Node *nextbegin=end->next;reverse(begin,end);pre->next=end;pre=begin;begin=end=nextbegin;}}return cur;}int main(){int a[]={1,2,3,4,5,6,7,8,9,10,11,12};Node* nd[12];for(int i=0;i<12;i++){nd[i]=new Node;nd[i]->next=NULL;nd[i]->data=a[i];}for(int i=0;i<11;i++){nd[i]->next=nd[i+1];}Node *tmp=reverseAll(nd[0],4);for(;tmp!=NULL;tmp=tmp->next){cout<<tmp->data<<endl;}system("pause");return 0;}