C语言单链表插入基础


1实现目标:输入数据如0 2 4 8,插入数据n,如果比第一个大,插入到第一个前面,否则继续找下一个,直到找到比n小的,查到他的前面

2此程序,把大于大于第一个数作为特殊处理

#include<stdio.h>

#include<stdlib.h>

#define FAILURE 0
#define SUCESS 1


struct node{
    int num;
    struct node *next;
};

typedef struct node Node;

Node *creat_link(void);                    //【创建链表】
void show_creat_link(Node *root);        //【显示链表】
int add_data(Node **root,int new_value);//【添加数据到链表】

int main(void)
{
    int value;
    Node *head=creat_link();
    puts("the data you entered is:");
    show_creat_link(head);

    puts("enter the number you wan to in");
    while((scanf("%d",&value))!=1)
    {
        while(getchar()!='\n')
            continue;
        puts("enter a number ");
    }

    add_data(&head,value);
    puts("after input the data is");
    show_creat_link(head);

    return 0;
}


/*********【创建链表】***********/
Node *creat_link(void)
{
    int number;
    Node *cur ,*pre,*head;
    head=NULL;

    puts("enter a number (q to quit)");
    for(;scanf("%d",&number)==1;)
    {
        cur=(Node *)malloc(sizeof(Node));
        if(cur==NULL)
            return FAILURE;

        if(head==NULL)
            head=cur;
        else
            pre->next=cur;

        cur->next=NULL;

        cur->num=number;

        while(getchar()!='\n')
            continue;
        pre=cur;
        puts("enter next number (q to quit)");
    }

    while(getchar()!='\n')
            continue;

    return head;
}
/******【显示链表】********/
void show_creat_link(Node *root)
{
    Node *current;
    current=root;
    if(current!=NULL)
    {
        while(current!=NULL)
        {
            printf("%d\n",current->num);
            current=current->next;
        }
    }
    else
        puts("no data entered or something error in the add_data");
}

/******【添加数据到链表】********/
int add_data(Node **root,int new_value)
{
    Node *cur,*pre,*new_node;
    
    cur=*root;
    pre=NULL;

    while(cur!=NULL&&cur->num > new_value)
    {
        pre=cur;
        cur=cur->next;
    }

    new_node=(Node *)malloc(sizeof(Node));
    if(new_node==NULL)
            return FAILURE;

    new_node->num=new_value;

    new_node->next=cur;

    if(pre==NULL)
        *root=new_node;
    else
        pre->next=new_node;

    return SUCESS;

}


/【优化过后的程序】///

/******【添加数据到链表】********/
int add_data(register Node **rootptr,int new_value)
{
    register Node *current, *new_node;

    while((current= *rootptr)!=NULL&&current->num>new_value)
            rootptr=&(current->next);          //rootptr就可以指向结构中的next 字段,也包括根指针

    new_node=(Node *)malloc(sizeof(Node));
    if(new_node==NULL)
            return FAILURE;

    new_node->num=new_value;

    new_node->next=current;
    *rootptr=new_node;
    
    return SUCESS;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值