第十九周项目一:动态链表体验(六):将值为X的结点插入到升序的链表中

来源:互联网 发布:数据库怎么设置外键 编辑:程序博客网 时间:2024/04/30 01:23
/**copyright (c) 2014, 烟台大学计算机学院.*All rights reserved.*文件名称:test.cpp *作者:陆云杰*完成日期:2015年1月27日 *版本号:v1.0* **问题描述:动态链表体验*程序输入:数据*程序输出:将值为X的结点插入到升序的链表中后的数据*/#include <iostream>using namespace std;struct Node{    int data;    struct Node *next;};Node *head=NULL;void make_list3();void out_list();void insert();int main( ){    make_list3();    out_list();    insert();    out_list();    return 0;}void make_list3(){    int n;    Node *t,*p,*q;    cout<<"输入若干正数(以0或一个负数结束)建立链表:"<<endl;    cin>>n;    while(n>0)    {        t=new Node;        t->data=n;        t->next=NULL;        if(head==NULL)            head=t;        else        {            if(n<=head->data)            {                t->next=head;                head=t;            }            else            {                p=head;                q=p->next;                while(q!=NULL&&n>q->data)                {                    p=q;                    q=p->next;                }                if(q==NULL)                {                    p->next = t;                }                else                {                    t->next=q;                    p->next=t;                }            }       }        cin>>n;    }    return;}void out_list(){    Node *p=head;    cout<<"链表中的数据为:"<<endl;    while(p!=NULL)    {        cout<<p->data<<" ";        p=p->next;    }    cout<<endl;    return;}void insert(){    Node *t,*p,*q;    int n;    cout<<"请输入想要插入的数据:"<<endl;    cin>>n;    if(n>0)    {        t=new Node;        t->data=n;        t->next=NULL;        if(n<head->data)        {            t->next=head;            head=t;        }        else        {            p=head;            q=head->next;            while(q!=NULL&&n>q->data)            {                p=q;                q=q->next;            }            if(q==NULL)            {                q->next=t;            }            else            {                p->next=t;                t->next=q;            }        }    }    else cout<<"输入数据不符!"<<endl;}

学习心得:方法和上一题类似!

0 0
原创粉丝点击