【问题标题】:copy elements of an array to a linked list in C将数组的元素复制到C中的链表
【发布时间】:2012-01-13 03:52:30
【问题描述】:

我有一个数组,我想通过将我的元素传输到节点来从中创建一个双向链表。并通过指针(上一个和下一个)链接它们 我所做的是

head = malloc(sizeof(struct)) 头->上一页=空 头->下一个=NULL 尾=头

for(i=0;i<num;i++){
    //copy data from arr[i] to tail
    temp=tail
    tail->next=malloc(sizeof(struct))
    tail=tail->next
    tail->prev=temp
}

现在,我如何复制数据? temp、head 和 tail 是结构体的指针

【问题讨论】:

  • 那么,您的问题是什么?您是否因为代码不是有效的 C 而收到编译器错误?或者那不是您所做的,而是您认为要记住您所做的事情(因为如上所述,这不是有效的 C)?
  • 好的,但是这个结构的内容是什么?
  • 我想将 arr[i] 的数据复制到 temp
  • 结构 a{ 结构 b b1[33];结构 c c1[128]; ..
  • 你当然可以使用memcpy,但是很难说你的问题是什么。你只说你想做的事,但不说你为什么失败。再说一次,您发布的代码不是有效的 C,所以它要么不完全是您所做的,要么可能是您的问题,因为您无法编译。

标签: c arrays structure


【解决方案1】:

我猜你没有尝试编写和编译。 链表的元素至少应该有一些地方来保存数组中的值,比如说 int 类型的数据。

#include <stdio.h>
#include <malloc.h>
#define N 3

typedef struct a{
struct a* prev;
struct a* next;
int data;
}item;

int main(void)
{
item* head;
item* tail;
item* temp;
int num = N;
int data[N] = {1,2,3}; /*initialization*/
int i = 0;
head = (item*)malloc(sizeof(item));
head -> prev = NULL;
head -> next = NULL;
tail = head;
for(i = 0; i < num; i ++){
    temp = tail;
    tail -> next = (item*)malloc(sizeof(item));
    tail = tail -> next;
    tail -> next = NULL;
    tail -> data = data[i];
    tail -> prev = temp;
}
for(temp = head -> next; temp != NULL; temp = temp -> next) /*the following is for testing purpose*/
    printf("%d\t", temp -> data);
return 0;
}

请注意,head 元素不包含您想要的内容。

【讨论】:

    【解决方案2】:

    创建临时节点并解析从到最后一个节点的链接列表分配这些详细信息

    counter=start_node;
         temp=(struct NODE *)malloc(sizeof(struct NODE));   /*create new node*/
                    temp->node_data=data;                               /*set data in new node*/
                    while(counter -> next_node!=NULL)
                    {
                        counter=counter->next_node;             /*increment in counter*/
                    }
    
              temp->prev_node=counter;          /*set next node of new node*/
              counter->next_node = temp;
              temp->next_node = null;
    

    这里 temp 是当前节点。

    【讨论】:

    • 我很难理解你在说什么。
    【解决方案3】:

    你需要保存tail-&gt;prev,所以你可以这样做:

    node * tailPrev = tail->prev;
    memcpy(tail, &arr[i], sizeof(*tail));
    tail->prev = tailPrev;
    //continue with your code...
    

    【讨论】:

      猜你喜欢
      • 2018-04-22
      • 2012-11-06
      • 2017-04-25
      • 1970-01-01
      • 1970-01-01
      • 2021-02-11
      • 1970-01-01
      • 2020-02-29
      • 2023-02-12
      相关资源
      最近更新 更多