a597677400 2015-04-09 08:34 采纳率: 100%
浏览 4113
已采纳

有序单链表的实现 C++

#include
using namespace std;
struct Node
{ int data;
Node *next;
};
void insert(Node *&head,int num)
{ Node *s,*p,*q;
s=new Node;
s->data=num;
s->next=NULL;
if(head==NULL)
{ head=s;
return;
}
if(head->data>s->data)
{ s->next=head;
head=s;
return;
}
for(q=head,p=head->next;p;q=p,p=p->next)
if(p->data>s->data)
{ s->next=p;
q->next=s;
return;
}
q->next=s;
return;
}
void ShowNode( Node *head)
{cout<<"now the items of list are:";
while(head)
{ cout<data<<" ";
head=head->next;}
cout< }
void ReverseList(Node *head)
{ cout Node *s,*p,*q;
if(head==NULL||head->next==NULL)
{return;}
s=head->next;
p=s->next;
s->next=NULL;
while(p)
{q=s->next;
p->next=s;
s=p;
p=q;
head->next=s;
cout<data<<" ";
head=head->next;
}cout< }
int main()
{ int k;
Node *head=NULL;
cin>>k;
while(k!=0)
{insert(head,k);
cin>>k;}
ShowNode(head);
ReverseList(head);
}

这是我的代码,有序输出可以用,但逆序输出元素就不成功。求大神,教改程序。

  • 写回答

3条回答 默认 最新

  • threenewbee 2015-04-09 12:41
    关注

    http://codepad.org/uXUnowLl

     #include<iostream>
    using namespace std;
    struct Node
    { int data;
      Node *next;
    };
    void insert(Node *&head,int num)
    { Node *s,*p,*q;
      s=new Node;
      s->data=num;
      s->next=NULL;
      if(head==NULL)
      { head=s;
        return;
      }
      if(head->data>s->data)
      { s->next=head;
        head=s;
        return;
      }
      for(q=head,p=head->next;p;q=p,p=p->next)
       if(p->data>s->data)
       { s->next=p;
         q->next=s;
         return;
       }
       q->next=s;
       return;
    }
    void ShowNode( Node *head)
    {cout<<"now the items of list are:";
     while(head)
     { cout<<head->data<<" ";
       head=head->next;}
       cout<<endl;
    }
    void ReverseList1(Node *head1)
    {
    if (head1->next != NULL)
    ReverseList1(head1->next);
    cout<<head1->data<<" ";
    }
    void ReverseList(Node *head)
    { cout<<"now the change items of list are:";
    /*    Node *s,*p,*q;
     if(head==NULL||head->next==NULL)
      {return;}
      s=head->next;
      p=s->next;
      s->next=NULL;
      while(p)
      {q=s->next;
        p->next=s;
        s=p;
        p=q;
        head->next=s;
    cout<<head->data<<" ";
       head=head->next;
       }cout<<endl;
    */
    ReverseList1(head);
    }
    
    
    int main()
    { int k;
      Node *head=NULL;
    for (k=1; k <= 5; k++)
        insert(head,k);
    ShowNode(head);
    ReverseList(head);
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?