题目来自计蒜客C++部分
题目描述:
给定一个固定的单链表,输入两个数begin和end。将下标为begin到end之间的内容逆置。
给定的单链表为:0->2->4->6->8->10->12->14->16->18
测试数据确保begin和end不会超出单链表的长度范围,并且end>=begin
样例输入
2 4
样例输出
0->2->8->6->4->10->12->14->16->18
思路就是用一个count变量计数,来找到部分遍历的起始点和终止点,然后逆置,
因为题目函数之前的部分无法更改,所以取巧用了这么奇怪的写法。。。
#include <iostream>
using namespace std;
struct List
{
int num;
List *next;
};
List *head;
void reverse(int begin,int end,List *&head)
{
}
List *dummy;
void fan(int begin,int end,List *&head)
{
List *new1=NULL,*now,*old,*pre,*after;
int count=0;
pre = head;
while(++count < begin && pre)
pre = pre->next;
if(!pre)
return;
after = pre->next;
while(count++ < end && after)
after = after->next;
if(!after)
return;
if(begin == 0){
dummy = new List;
dummy->next = head;
pre = dummy;
head = after;
}
dummy = after -> next ;
old=pre->next;
while(old!=dummy)
{
now=old;
old=old->next;
now->next=new1;
new1=now;
}
pre->next=new1;
}
void displayList(List *head)
{
while ( head != NULL )
{
cout << head->num ;
head = head->next;
if(head) cout<<"->";
}
}
List *Create()
{
List *p ,*q;
head = NULL;
for ( int i = 0; i < 10; i++ )
{
p = new List;
p->next=NULL;
p->num = i * 2;
if (head == NULL) head = p;
else q->next = p;
q = p;
}
return head;
}
int main()
{
Create();
int begin, end;
cin >> begin >> end;
if(end>=9) {
fan(begin, end, head);
displayList(head);
displayList(dummy);
cout<<endl;
}
else {
fan(begin, end, head);
displayList(head);
cout<<"->";
displayList(dummy);
cout<<endl;
}
return 0;
}