这么写有什么不对吗,为什么它运行不了?有些不太理解,希望有人能具体解惑一下,如果可以的话,请讲的简单易懂一点。
#include
#include
typedef struct Node {
int Data;
struct Node *Next;
}node,*List;
List Read();
void Print( List L );
List Insert( List L, int X );
int main()
{
List L;
int X;
L = Read();
scanf("%d", &X);
L = Insert(L, X);
Print(L);
return 0;
}
List Insert( List L, int X )
{
List pr;
pr=(List)malloc(sizeof(struct Node));
if(X<=L->Data){
pr->Next=L;
pr->Data=X;
return pr;
}else{
if(L->Next==NULL){
L->Next=pr;
pr->Data=X;
pr->Next=NULL;
}else{
L->Next=Insert(L->Next,X);
}
}
return L;
}
List Read(){
List L,h;
L=h=(List)malloc(sizeof(struct Node));
int i,n;
scanf("%d",&n);
for(i=1;i<=n;i++){
L=(List)malloc(sizeof(struct Node));
scanf("%d",L->Data);
L=L->Next;
}
L->Next=NULL;
L=h->Next;
free(h);
h=L;
return h;
}
void Print( List L){
while(L->Next!=NULL){
printf("%d",L->Data);
L=L->Next;
}
}
目测有3个错误
List Insert(List L, int X) 函数中应该先判断 L 是否为 NULL。
scanf("%d", L->Data) 应该改为 scanf("%d", &(L->Data))。
Print 函数中的 while(L->Next!=NULL) 应该改为 while(L!=NULL)。
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int Data;
struct Node *Next;
} node, *List;
List Read();
void Print(List L);
List Insert(List L, int X);
int main()
{
List L;
int X;
L = Read();
scanf("%d", &X);
L = Insert(L, X);
Print(L);
return 0;
}
List Insert(List L, int X)
{
if (L == NULL) {
L = (List)malloc(sizeof(struct Node));
L->Data = X;
L->Next = NULL;
} else {
if (X <= L->Data) {
List pr;
pr = (List)malloc(sizeof(struct Node));
pr->Next = L;
pr->Data = X;
L = pr;
} else {
L->Next = Insert(L->Next, X);
}
}
return L;
}
List Read()
{
List L, h;
L = h = (List)malloc(sizeof(struct Node));
int i, n;
scanf("%d", &n);
for (i = 1; i <= n; i++) {
L->Next = (List)malloc(sizeof(struct Node));
scanf("%d", &(L->Next->Data));
L = L->Next;
}
L->Next = NULL;
L = h->Next;
free(h);
h = L;
return h;
}
void Print(List L)
{
while (L != NULL) {
printf("%d ", L->Data);
L = L->Next;
}
}
//这里其实本质上是用来选择排序的思想,选出一个数,放到他该有的位置上。
size_t end = n - 1;
while (end > 0)
{
swap(&a[end], &a[0]);
Adjustdown(a, end, 0);
end--; //--之后代表最后一个元素的位置,没减之前代表需要调整的元素个数。
}
选好一个数之后就放到该有的位置上,然后调整剩下的,使之还是一个堆,用向下调整算法去调整。