这个输出不带头结点的单链表的代码哪里错了??

问题描述:

#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"
typedef int ElemType;
typedef struct node
{
ElemType data;
struct node next;
}Node;
void CreatList(Node *&L,ElemType a[],int n)
{
Node *s,*r;
int i;
L=(Node *)malloc(sizeof(Node));
r=0;
for(i=0;i {
s=(Node *)malloc(sizeof(Node));
s->data=a[i];
r->next=s;
r=s;
}
r->next=NULL;
}
void DispList(Node *L)
{
Node *p=L->next;
while(p!=NULL)
{
printf("%d",p->data);
p=p->next;
}
printf("\n");
}
int main(int argc, char
argv[])
{
Node *L;
int a[10]={1,2,3,4,5,6,7,8,9,0};
CreatList(L,a,10);
DispList(L);
return 0;
}

或者改一下下面这个方法void CreatList(Node *&L,ElemType a[],int n)
{
Node *s;
int i;
L=(Node *)malloc(sizeof(Node)); L -> next = NULL ;
s=(Node *)malloc(sizeof(Node)); for(i=0;i <n ,i ++){

s->data=a[i];
s->next=L -> next;
L ->next = S;
}
}
CreatList 方法里 就一个指针就行 最后不知道对不对 也没运行 没对的话,自己再改改吧!

1.next应该是指针类型
2.r =(Node *)malloc(sizeof(Node));
3.r ->next = a[0 ]

void CreatList(Node *&L, ElemType a[], int n)
{
    Node *s, *r;
    int i;
    L = (Node *)malloc(sizeof(Node));
    r = L; //注意这里,你需要将建的List与L联系起来
    for (i = 0; i < n; i++ )
    {
        s = (Node *)malloc(sizeof(Node));
        s->data = a[i];
        r->next = s;
        r = s;
    }
    r->next = NULL;
}