c - 如何实现【复制数组到链表】功能?

标签 c arrays pointers linked-list

这应该做的是:

  • 创建一个包含 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);
}

如何解决?

最佳答案

您不需要将 head 传递给 copy 函数,因为它是全局的,当您这样做时,您会创建一个名为 head 的本地指针,它函数一结束就会被销毁。

所以复制应该是这样的

void copy(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;
     }  
}

同时打印时将 while 更改为

while(temp!=NULL)
    {
      printf(" %d ",temp->data);
      temp=temp->next;

    }

关于c - 如何实现【复制数组到链表】功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42981797/

相关文章:

C 获取对象的所有引用?

c - 收到 "bus error 10"错误消息?

c - 在 C 中使用数组的垃圾值

c - 减去 3d 数组中的地址

ruby-on-rails - 如何将我的字符串转换为数组? (JSON.parse 错误)

C...字符串分割问题

php - 在 foreach 循环中追加数组的方法比较

php - 根据父/子关系对数组值进行排序

c - 对 'xcb_event_get_label' 的 undefined reference

c++ - 计算 float 后下一个更高整数的有效方法?