求助大神,创建链表就是不成功,虽然可以运行。QAQ
#include<stdio.h>#include<stdlib.h>
struct test{
int data;
struct test *next;
};
void Creatlist(struct test *head, int a[], int n);
void Printelem(struct test *head);
void Free(struct test *head);
int main()
{
struct test *head;
int i = 0,j=1;
int a;
for(i;i<40;i++,j+=3)
{
a=j;
}
Creatlist(head,a,10);
Printelem(head);
Free(head);
}
void Creatlist(struct test *head, int a[], int n)
{
struct test *p,*s;
int i;
head = (struct test*)malloc(sizeof(struct test));
head->next = NULL;
head->data = n;
p = head;
for(i=0;i<n;i++){
s = (struct test*)malloc(sizeof(struct test));
s->data = a;
p->next = s;
p = p->next;
printf("%d\n",p->data);
}
p->next = NULL;
printf("创建完成\n");
}
void Printelem(struct test *head)
{
struct test *p = head;
int j = 1;
while(p!=NULL){
printf("%d\t%d\n", j, p->data);
p = p->next;
j++;
}
printf("输出完成;\n");
}
void Free(struct test *head)
{
struct test *p = NULL, *ps;
ps = head;
while(ps){
p = ps;
ps = head->next;
free(p);
}
printf("释放完成\n");
} 如果参数作为输出参数想返回一个地址,参数就要是一个二级指针,void Creatlist(struct test **head, int a[], int n),使用的时候给head的地址Creatlist(&head,a,10);函数中这样*head = (struct test*)malloc(sizeof(struct test)); 修改了一下,可以正常运行。
1. 声明部分struct test *Creatlist(struct test *head, int a[], int n);
2. 主函数里head = Creatlist(head,a,10);
3. CreateList()函数部分函数类型为struct test *Creatlist(struct test *head, int a[], int n),结尾 return head;
4. Free()函数部分 只需要一个指针 struct test *ps = head;
while( head ){
ps = head->next;
free(head);
head = ps;
}
5. 望采纳。。。
页:
[1]