寒假自主学习项目一 - 链表(6、插入节点)

/*
 *Copyright(c)2014,烟台大学计算机学院
 *All rights reserved.
 *文件名称:test.cpp
 *作者:满星辰
 *完成日期:2014年 2月 4日
 *版本号:v1.0
 *问题描述:编写函数void insert(int x),将值为x的结点插入到由make_list3建立起来的有序链表中。
 *输入描述:链结的数据
 *程序输出:
 */
#include  <iostream>
using namespace std;
struct Node
{
    int data;            //结点的数据
    struct Node *next;  //指向下一结点
};
Node *head=NULL;    //将链表头定义为全局变量,以便于后面

操作
void make_list3();  //建立升序链表
void out_list();    //输出链表
void insert(int x); //将值为x的结点插入到由make_list3建立

起来的有序链表中
int main( )
{
    int x;
    make_list3();
    out_list();
    cout<<"请输入要插入的正整数x:";
    cin>>x;
    insert(x);
    out_list();
    return 0;
}
void make_list3()
{
    int n;
    Node *p,*x,*y;
    cout<<"输入若干正数(以0或一个负数结束)建立链表:";
    cin>>n;
    while(n>0)
    {
        p=new Node;
        p->data=n;
        p->next=NULL;
        if(head==NULL)
        {
            head=p;
        }
        else
        {
            if(n<=head->data)
            {
                p->next=head;
                head=p;
            }
            else
            {
                x=head;
                y=x->next;
                while(y!=NULL&&n>y->data)
                {
                    x=y;
                    y=x->next;
                }
                if(y==NULL)
                {
                    x->next=p;
                }
                else
                {
                    p->next=y;
                    x->next=p;
                }
            }
        }
        cin>>n;
    }
    return;
}
void out_list()
{
    Node *p=head;
    cout<<"链表中的数据为:"<<endl;
    if(p==NULL)
        cout<<"空链表!";
    while(p!=NULL)
    {
        cout<<p->data<<" ";
        p=p->next;
    }
    cout<<endl;
    return;
}
void insert(int x)
{
    Node *p,*m,*n;
    p->data=x;
    if(x<head->data)
    {
        p->next=head;
        head=p;
    }
    else
    {
        m=head;
        n=m->next;
        while((n!=NULL)&&(x>n->data))
        {
            m=n;
            n=n->next;
        }
        if(n==NULL)
        {
            m->next=p;
        }
        else
        {
            p->next=n;
            m->next=p;
        }
    }
    return;
}

示例图片:

 


学习心得:

如果只是执行“插入”这个动词,在这方面链表比数组可要简单多了,不用循环什么的,直接把前一个的 next 赋值为 要插入的这一个,再把这一个的 next  赋值为 后一个。

So easy~\(≧▽≦)/~可是还要考虑各种情况,特殊的就第一个和最后一个。。。

想起来漏洞在哪就加上去,最后成果简直不忍直视,So,偷偷参考一下别人的~~嗯嗯,现在是我的了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值