C代码_链表精粹

一下这段代码仔细研读、不错

#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
    float v;
    struct node * next;
    struct node *left, *right;
}Node, *pNode,*List;
 
List create(void)
{
    List head, p, pre;
    float v;
    printf("input a increasing array, and stop with a smaller value. the last value will be ignored\n");
    printf("e.g. 1 2 3 4 5 6 0, the array is 1 2 3 4 5 6\n");
    head = p = pre = NULL;
    while(scanf("%f", &v) == 1)
    {
        if(pre && pre->v >= v)
            break;
        p =(List)malloc(sizeof *p);// 想表达什么意思
        p->v = v;
        p->next = p->left = p->right = NULL;
        if(pre == NULL)
            head = pre = p;
        else 
        {
            pre->next = p;
            pre = p;
        }
    }
    return head;
}
void print_node(pNode p)
{
    if(p)
    {
        printf("%f(", p->v);
         
        if(p->left) printf("%f,", p->left->v);
        else printf("null,");
        if(p->right) printf("%f)", p->right->v);
        else printf("null)");
        if(p->next) printf("->%f", p->next->v);
        printf("\n");
    }
}
void print_list(List head)
{
    if(head)
    {
        print_node(head);
        if(head->next) print_list(head->next);
        if(head->left) print_list(head->left);
        if(head->right)print_list(head->right);
    }
}
List delete_list(List head)
{
    if(head->next) delete_list(head->next);
    if(head->left) delete_list(head->left);
    if(head->right) delete_list(head->right);
    free(head);
    return NULL;
}
List parse(List head)
{
    List h = head;
    float min;
    pNode pre, p, k;
    while(h->next)
    {
        k = h;
        pre = NULL;
        min = (h->next->v - h->v);
        while(k->next->next)
        {
            if(min > (k->next->next->v - k->next->v))
            {
                min =(k->next->next->v - k->next->v); 
                pre = k;
            }
            k = k->next;
        }
        p = (List)malloc(sizeof *p);
        if(pre)
        {
            p->left = pre->next;
            p->right = pre->next->next;
            p->next = p->right->next;
            pre->next = p;
        }
        else
        {
            p->left = h;
            p->right = h->next;
            p->next = h->next->next;
            h = p;
        }
        p->v = (p->left->v + p->right->v) / 2;
        p->left->next = p->right->next = NULL;
    }
    return h;
}
int main()
{
    List head = NULL;
    head = create();
    head = parse(head);
    print_list(head);
    head = delete_list(head);
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值