代码:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int value;
struct node *next;
};
void sort_list(struct node *list); //用冒泡法实现链表的排序
void print_list(struct node *list); //打印
struct node *find_list(struct node *list, int key); //查找
struct node *delete_node(struct node *list, int key); //删除
struct node *insert_node(struct node *list, int key); //插入
int main(void)
{
struct node *first = NULL;
char a;
int key;
printf("选择要进行的操作:i-插入,f-查找,d-删除,p-打印,s-排序,*-退出\n");
while (1)
{
printf("输入要进行的操作:");
scanf("%c", &a);
while (getchar() != '\n')
;
if (a == '*')
break;
switch (a)
{
case 'i':
printf("输入要插入的数据:");
scanf("%d", &key);
while (getchar() != '\n')
;
first = insert_node(first, key);
break;
case 'f':
printf("输入要查找的数据:");
scanf("%d", &key);
while (getchar() != '\n')
;
if (find_list(first, key) != NULL)
printf("要查找的关键字地址为:%p\n", find_list(first, key));
else
printf("没找到!\n");
break;
case 'd':
printf("输入要删除的数据:");
scanf("%d", &key);
while (getchar() != '\n')
;
first = delete_node(first, key);
break;
case 's':
sort_list(first);
printf("\n");
break;
case 'p':
print_list(first);
printf("\n");
break;
default:
printf("输入错误,请重新输入!\n");
break;
}
}
return 0;
}
struct node *insert_node(struct node *list, int key)
{
struct node *new_node;
new_node =(struct node *) malloc(sizeof(struct node));
if (new_node == NULL)
{
printf("错误!");
exit(0);
}
new_node->value = key;
new_node->next = list;
return new_node;
}
struct node *delete_node(struct node *list, int key)
{
struct node *cur, *prev;
for (cur = list, prev = NULL; cur != NULL && cur->value != key; prev = cur, cur = cur->next) //定位key
;
if (cur == NULL) //没有找到
return list;
if (prev == NULL) //key在第一个节点,更新first的值
list = list->next;
else //找到key的位置
prev->next = cur->next;
free(cur); //释放内存
return list;
}
struct node *find_list(struct node *list, int key)
{
while (list != NULL && list->value != key)
list = list->next;
return list;
}
void print_list(struct node *list)
{
struct node *p;
printf("%4d", list->value);
p = list->next;
while (p != NULL)
{
printf("%5d", p->value);
p = p->next;
}
}
void sort_list(struct node *p)
{
struct node *a = p;
int temp, flag = 0;
for (;;)
{
for (p = a, flag = 0; p != NULL && p->next != NULL; p = p->next)
{
if (p->value >= (p->next)->value)
{
temp = (p->next)->value;
(p->next)->value = p->value;
p->value = temp;
flag++;
}
}
if (!flag)
break;
}
}
运行结果: