#include <stdio.h>
#include <stdlib.h>
//链表节点的信息
struct node
{
int num;
char name[32];
struct node *next;
};
struct node*create_node()
{
struct node *pnew = NULL;
pnew = (struct node*)malloc(sizeof(struct node));
if(NULL == pnew)
{
printf("malloc error! %s, %d\n", __FILE__, __LINE__);
exit(-1);
}
pnew->next = NULL;
return pnew;
}
void list_insert(struct node *head)
{
//1、创建新的节点
struct node *pnew = NULL;
pnew = create_node();
printf("请输入学号:");
scanf("%d", &pnew->num);
while(getchar()!='\n');
printf("请输入姓名:");
scanf("%s", pnew->name);
while(getchar()!='\n');
//2、加入链表
#if 0
if(head->next == NULL)//空链表
{
head->next = pnew;
}
else
{
pnew->next = head->next;
head->next = pnew;
}
#endif
pnew->next = head->next;
head->next = pnew;
return ;
}
void show_list(struct node *head)
{
if(head->next == NULL)
{
printf("空链表!\n");
return ;
}
struct node *p = head->next;
while(p!=NULL)
{
printf("[%d %s %p]-->", p->num, p->name,p->next);
p = p->next;
}
printf("\n");
}
//查找操作
struct node *list_search_by_num(struct node *head, int num)
{
struct node *p = head->next;
while(p != NULL)
{
if(p->num == num)
{
return p;
}
p = p->next;
}
return NULL;
}
//删除操作
//成功: 0
//失败:-1
int list_del_by_num(struct node *head, int num)
{
//查找学号是否存在
struct node *pdel = NULL;
pdel = list_search_by_num(head, num);
if(NULL == pdel)
{
printf("删除失败,学号不存在!\n");
return -1;
}
//删除操作
struct node *p = head;
while(p->next != pdel)
{
p = p->next;
}
p->next = pdel->next;
free(pdel);
return 0;
}
//释放操作
struct node* list_free(struct node *head)
{
struct node *pdel = NULL;
while(head != NULL)
{
pdel = head;
head = head->next;
free(pdel);
}
return head;
}
//排序操作
void list_sort(struct node *head)
{
struct node *new_head = NULL;
struct node *pmax = NULL;
struct node *head1 = head->next;
head->next = NULL;
struct node *p = NULL;
while(head1 != NULL)
{
//找最大值
p = head1;
pmax = head1;
while(p!=NULL)
{
if(p->num > pmax->num)
{
pmax = p;
}
p = p->next;
}
//将最大值从head1链表中移除
if(pmax == head1)
{
head1 = head1->next;
}
else
{
p = head1;
while(p->next != pmax)
{
p = p->next;
}
p->next = pmax->next;
}
pmax->next = NULL;
//加入新的链表
pmax->next = new_head;
new_head = pmax;
}
head->next = new_head;
return ;
}
int main()
{
struct node *head = NULL;
head = create_node();
for(int i=1; i<=3; i++)
{
list_insert(head);
}
show_list(head);
#if 0
int num;
printf("请输入删除的学号:");
scanf("%d", &num);
list_del_by_num(head, num);
#endif
list_sort(head);
show_list(head);
return 0;
}