您的位置:首页 > 其它

第十八周项目一(6):将值为x的结点插入到建立起来的有序链表中

2015-01-31 19:47 204 查看
问题及代码:

/*
*Copyright (c)2014,烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:动态链表体验.cpp
*作    者:白云飞
*完成日期:2015年1月31日
*版 本 号:v1.0
*
*问题描述:编写函数void insert(int x),将值为x的结点插入到由make_list建立起来的有序链表中。
*程序输入:输入若干正数(以0或一个负数结束)建立链表。
*程序输出:输出升序后的所有的数。
*/
#include  <iostream>
using namespace std;
struct Node
{
    int data;            //结点的数据
    struct Node *next;  //指向下一结点
};
Node *head=NULL;    //将链表头定义为全局变量,以便于后面操作
void make_list();   //建立链表
void out_list();    //输出链表
void insert(int x); //排序
int main( )
{
    make_list();
    out_list();
    int x;
    cout<<"请输入要插入的数:";
    cin>>x;
    insert(x);
    out_list();
    return 0;
}
void make_limake_listst()
{
    int n;
    cout<<"输入若干正数(以0或一个负数结束)建立链表:";
    cin>>n;
    while(n>0)//输入若干正数建立链表,输入非正数时,建立过程结束
    {
        insert(n);//调用insert
        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(int x)
{
    Node *p,*q,*f;
    p=new Node; //新建结点
    p->data=x;
    p->next=NULL;
    if(head==NULL)
        head=p;
    else
    {
        if(head->data>x)
        {
            p->next=head;
            head=p;
        }
        else
        {
            f=head;
            q=f->next;
            while(q!=NULL&&x>q->data)
            {
                f=q;
                q=f->next;
            }
            if(q==NULL)
            {
                f->next=p;
            }
            else
            {
                p->next=q;
                f->next=p;
            }
        }
    }
    return;
}


运行结果:



学习心得:

在上一篇的基础上,对make_list进行修改,添加了自定义函数insert。


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐