一下这段代码仔细研读、不错
#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;
}