开发者社区> 问答> 正文

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);
}

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

展开
收起
a123456678 2016-03-06 09:37:21 2353 0
1 条回答
写回答
取消 提交回答
  • #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);
    }
    2019-07-17 18:54:01
    赞同 展开评论 打赏
问答分类:
C++
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
使用C++11开发PHP7扩展 立即下载
GPON Class C++ SFP O;T Transce 立即下载
GPON Class C++ SFP OLT Transce 立即下载