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&¤t->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;
}