周记4(带头节点)

#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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值