链表翻转。给出一个链表和一个数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→6→5,用程序实现
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct ListNode
{
int val;
ListNode *link;
ListNode(int v):val(v),link(NULL){ }
};
ListNode* reverse(ListNode *first, ListNode *second)
{
if(first->link==second)
return first;
ListNode *temp=first->link;
ListNode *pAhead=first->link,*pMid=pAhead->link,*pBehind=NULL;
pAhead->link=second->link;
while (pMid!=second)
{
pBehind=pMid->link;
pMid->link=pAhead;
pAhead=pMid;
pMid=pBehind;
}
second->link=pAhead;
first->link=second;
return temp;
}
ListNode* reverseList(ListNode *head, int k)
{
if(k==0||k==1)
return head;
ListNode *leader=new ListNode(0);
leader->link=head;
ListNode *fisrt=leader,*second=NULL,*temp=NULL;
int k_backup=k;
if(k>6)
{
second=fisrt->link;
while (second!=NULL)
{
temp=second;
second=second->link;
}
reverse(fisrt,temp);
}
else
{
while (head!=NULL)
{
temp=head;
head=head->link;
k--;
if(k==1)
{
second=head;
fisrt=reverse(fisrt,second);
k=k_backup;
head=fisrt->link;
temp=head;
}
}
if(fisrt->link!=NULL)
{
reverse(fisrt,temp);
}
}
temp=leader->link;
delete leader;
return temp;
}
int main()
{
int n=6,k;
cin>>k;
ListNode *head=new ListNode(1);
ListNode *temp=head;
for (int i=2;i<=n;i++)
temp->link=new ListNode(i),temp=temp->link;
temp=reverseList(head,k);
while(temp!=NULL)
{
cout<<temp->val<<' ';
temp=temp->link;
}
cout<<endl;
system("pause");
return 0;
}