单链表部分逆置

题目来自计蒜客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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值