#include<stdio.h>
#include<malloc.h>
typedef struct node
{
int data;
struct node *next;
}Node, *Linklist;
int node_num = 0;
void creat(Node *head); //创建链表
void print(Node *head); //输出链表
Node *query(Node *head, int value); //查找
void *del_node(Node *head, int value); //对链表的删除节点
void insert_node(Node *head, Node * inser); //插 入 到 有 序 的 链 表
int main(void)
{
int value;
Node *head, *inser;
head = (Node *)malloc(sizeof(Node));
head->next = NULL;
creat(head);
print(head);
getchar();
getchar(); //当以IF里调用函数,必须加getchar(),假如调用函数不在IF里, 单独作为一句调用,可以不用getchar();
printf("请输入要查找的数值:/n");
scanf("%d", &value);
getchar();
if (NULL == query(head, value))
{
printf("not found!/n");
}
else
{
printf("找到了,地址是%p/n", query(head, value));
}
printf("请输入要删除的数值:/n");
scanf("%d", &value);
del_node(head, value);
print(head);
printf("请输入要插入的数字/n");
/**/inser = (Node *)malloc(sizeof(Node)); //开始做的时候忽略了, 犯了大错啦,指针不初始化是不能存东西的, 傻瓜!!!
scanf("%d", &inser->data) ;
insert_node(head, inser);
getchar();
printf("插入后的链表 为:/n");
print(head);
return 0;
}
void creat(Node *head) //head 不放数据的(数据结构书page45)
{
Node *p = head;
Node *s;
int data;
printf("建立新链表,输入非数字字符将结束输入:/n");
while(1 == scanf("%d",&data)) //用头插法
{
s = (Node *)malloc(sizeof(Node));
node_num = node_num +1;
s->data = data;
s->next = p->next;
p->next = s;
}
/*while (1 == scanf("%d", &data)) // 尾插法
{
s = (Node *)malloc(sizeof(Node));
s->data = data;
p->next = s;
p = s;
}
p->next = NULL;*/
}
void print(Node *head)
{
Node *p = head->next;
printf("链表的数据如下:/n");
while (p != NULL)
{
printf("%d/t", p->data);
p = p->next;
}
printf("/n");
}
Node * query(Node *head, int value)
{
Node *p = head;
while(p != NULL)
{
if (p->data == value)
return p;
else
p = p->next;
}
return NULL;
}
void *del_node(Node *head, int value)
{
Node *pre , *p ;
p = head->next;
pre = p;
while( p->data != value && p->next != NULL ) //查找过程
{
pre = p;
p = p->next;
}
if (p->data == value) //找到啦, (*^__^*) 嘻嘻……
{
/***/ if (p == head->next) //这个里面的IF是之后加上的啦, (*^__^*) 嘻嘻……
head->next = p->next;
else
{
pre->next = p->next ;
free(p);
return ;
}
}
else //没有找到, 嘿嘿
printf("没有找到要删除的节点!/n");
return ;
}
void insert_node(Node *head, Node * inser)
{
Node *p = head->next;
Node *pre = p;
if (head->next == NULL) //原表是空表
{
head->next = inser;
inser->next = NULL;
}
else
{
while (inser->data > p->data && p->next !=NULL)
{
pre = p;
p = p->next;
}
if(inser->data <= p->data) //找到位置插入
{
if (p == head->next) //插在表头之后
head->next = inser;
else //插在表中间
pre->next = inser;
inser->next = p;
}
else //搜集完了, 插在表尾
{
p->next = inser;
inser->next =NULL;
}
}
return;
}