这是什么应该做的是:如何实现[复制数组到链表]功能?
有4个元素创建一个数组。
打印这4个元素。
将数组元素复制到创建的链接列表中。
打印链接列表与打印和遍历功能。
我试过这个,它编译,但打印数组后崩溃。
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define ELEMENTS 4
struct node
{
int data;
struct node *next;
};
struct node*head;
void insert(int x)
{
struct node*temp= malloc(sizeof(struct node));
temp->data = x;
temp->next = NULL;
if(head != NULL) temp->next = head;
head=temp;
}
void copy(struct node*head ,int array[ELEMENTS],int n) //copying array elements and create linked list
{
struct node*temp = malloc(sizeof(struct node));
temp->data=array[0];
temp->next=NULL;
head =temp;
int i;
for(i=1;i<n;i++)
{
struct node*temp2= malloc(sizeof(struct node));
temp->next= temp2;
temp2->data = array[i];
temp2->next = NULL;
temp=temp2;
}
}
void printlist()
{
struct node*temp = head;
printf("List is : ");
while(temp->next!=NULL)
{
printf(" %d ",temp->data);
temp=temp->next;
}
printf("\n");
}
int main()
{
int *array=(int*)calloc(ELEMENTS , sizeof(int));
int i = 0;
for(i=0;i<ELEMENTS;i++)
{
printf("arrays = [%d] ",i);
scanf("%d", &array[i]);
}
for(i=0;i<ELEMENTS;i++) printf("array [%d] = %d \n", i,array[i]);
copy(head ,array[ELEMENTS],ELEMENTS);
printlist();
getchar();
return(0);
}
如何解决?
运行代码一个调试器并对其进行调试。 – barny