用内核链表提供的双向循环链表标准实现功能

来源:互联网 发布:淘宝卖了换钱什么意思 编辑:程序博客网 时间:2024/06/15 06:14
//用内核链表提供的双向循环链表标准实现//顺序递增存储若干自然数,比如输入一个整数10,//则建立一个双向循环链表,里面的每个节点分别存放1,2,3,4,5,6,7,8,9,10,//然后通过某些操作,将其重新排列成1,3,5,7,9,10,8,6,4,2,//即奇数升序偶数降序,并在屏幕上打印出来#include<stdio.h>#include<stdlib.h>#include"list.h"typedef int datatype;//包含数据的结构体typedef struct doublelist_head{    struct list_head ptr;//要有struct    datatype data;}double_list,*double_plist;extern void doublelist_init(double_plist *H);extern void doublelist_create(double_plist h);extern void doublelist_show(double_plist h);extern void doublelist_sort(double_list *head);int main(void){    double_list *head;    doublelist_init(&head);//初始化为头节点    doublelist_create(head);    doublelist_sort(head);    return 0;}//初始化,传入头指针的指针,才能改变实参void doublelist_init(double_plist *H){    *H = (double_plist)malloc(sizeof(double_list));//给头指针申请内存    if(NULL == *H)//一定要判断    {        perror("malloc failed\n");        exit(1);    }    INIT_LIST_HEAD(&(*H)->ptr);}//遍历void doublelist_show(double_plist h){    double_plist pos;//    printf("|_|");    list_for_each_entry(pos,&h->ptr,ptr)//@head:    the head for your list.        printf("----->%d",pos->data);    printf("\n");}//创建链表void doublelist_create(double_plist h){    int n,i;    double_plist new;    printf("请输入你要创建的个数:");    scanf("%d",&n);    for(i=0;i<n;i++)    {        new = (double_plist)malloc(sizeof(double_list));        if(NULL == new)        {            perror("malloc failed");            exit(1);        }        printf("请输入一个数据:");        scanf("%d",&new->data);//输入新结点数据        list_add_tail(&new->ptr,&h->ptr);//将新结点插入到表尾        doublelist_show(h);    }}//排序void doublelist_sort(double_plist h){    double_plist pos,tmp;    //pos指向头节点的前一个节点    pos = list_entry(h->ptr.prev,double_list,ptr);      while(pos != h)    {        if(pos->data%2 == 1)            pos = list_entry(pos->ptr.prev,double_list,ptr);//        else        {            tmp = pos;            pos = list_entry(pos->ptr.prev,double_list,ptr);//pos向前移动            list_move_tail(&tmp->ptr,&h->ptr);//tmp移动到尾部        }    }    printf("排序后:\n");    doublelist_show(h);}
原创粉丝点击