大家说下怎么把链表里面的数据放到一个数组里面
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int nDate;
struct node *pstnext;
}Node;
//链表建立
Node* creat()
{
Node *head = NULL, *p = NULL, *s = NULL;
int Date = 0, cycle = 1;
head = (Node*)malloc(sizeof(Node));
if(NULL == head)
{
printf("分配内存失败\r\n");
return NULL;
}
head->pstnext = NULL;
p = head;
while(cycle)
{
printf("请输入数据且当输入数据为0时结束输入\r\n");
scanf("%d", &Date);
if(0 != Date)
{
s = (Node*)malloc(sizeof(Node));
if(NULL == s)
{
printf("分配内存失败\r\n");
return NULL;
}
s->nDate = Date;
p->pstnext = s;
p = s;
}
else
{
cycle = 0;
}
}
p->pstnext = NULL;
return(head);
}
//链表输出
int output(Node *head)//获取数据元素个数n 为存放到数组做好准备
{
int n=0;
Node *p = head;
while(NULL != p)
{
n++;
printf("%d ", p->nDate);
p = p->pstnext;
}
printf("\r\n");
return n;
}
int *lookup(Node *head)//把链表的数据放到数组a[k]里面去
{
int k=output(head);
Node *p=head;
int a[k];
for(int i=0;i<k;i++)
{
a[i]=p->nDate;
p=p->pstnext;
}
return a;
}
int main()
{
int *a;
Node *head=creat();
int k=output(head);
//creat();
a=lookup(head);
for(int i=0;i<k;i++)
{
printf("%d ",a[i]);
}
return 0;
}
我的源代码 有错误如下 大家帮我看看
sd.c
C:\Documents and Settings\郑奇文\sd.c(67) : error C2057: expected constant expression
C:\Documents and Settings\郑奇文\sd.c(67) : error C2466: cannot allocate an array of constant size 0
C:\Documents and Settings\郑奇文\sd.c(67) : error C2133: 'a' : unknown size
C:\Documents and Settings\郑奇文\sd.c(68) : error C2143: syntax error : missing ';' before 'type'
C:\Documents and Settings\郑奇文\sd.c(68) : error C2143: syntax error : missing ';' before 'type'
C:\Documents and Settings\郑奇文\sd.c(68) : error C2143: syntax error : missing ')' before 'type'
C:\Documents and Settings\郑奇文\sd.c(68) : error C2143: syntax error : missing ';' before 'type'
C:\Documents and Settings\郑奇文\sd.c(68) : error C2065: 'i' : undeclared identifier
C:\Documents and Settings\郑奇文\sd.c(68) : warning C4552: '<' : operator has no effect; expected operator with side-effect
C:\Documents and Settings\郑奇文\sd.c(68) : error C2059: syntax error : ')'
C:\Documents and Settings\郑奇文\sd.c(69) : error C2143: syntax error : missing ';' before '{'
C:\Documents and Settings\郑奇文\sd.c(73) : warning C4172: returning address of local variable or temporary
C:\Documents and Settings\郑奇文\sd.c(83) : error C2143: syntax error : missing ';' before 'type'
C:\Documents and Settings\郑奇文\sd.c(83) : error C2143: syntax error : missing ';' before 'type'
C:\Documents and Settings\郑奇文\sd.c(83) : error C2143: syntax error : missing ')' before 'type'
C:\Documents and Settings\郑奇文\sd.c(83) : error C2143: syntax error : missing ';' before 'type'
C:\Documents and Settings\郑奇文\sd.c(83) : warning C4552: '<' : operator has no effect; expected operator with side-effect
C:\Documents and Settings\郑奇文\sd.c(83) : error C2059: syntax error : ')'
C:\Documents and Settings\郑奇文\sd.c(84) : error C2143: syntax error : missing ';' before '{'
执行 cl.exe 时出错.
sd.obj - 1 error(s), 0 warning(s)