复制链表 C 中的节点 [英] Copying nodes in linked list C
问题描述
我正在尝试复制链表中的节点.我不确定我是否做对了.我尝试制作测试用例,但没有成功.如果有人能告诉我我哪里出错了,我做对了什么,还有什么是测试我的代码的最佳方法.
I am trying to duplicate a node in linked list. I am not sure if I am doing it correctly. I tried making test cases but did they were not successful. If some one could tell me if where I went wrong and what I did right, also what is the best way to test my code.
struct node
{
int id;
char side;
int quantity;
double price;
};
struct onode
{
struct node* data;
struct onode* next;
struct onode* prev;
};
struct onode* newNode (struct node* data)
{
struct node* dataValue = (struct node*) malloc(sizeof(struct node));
struct onode* linkedlist = (struct onode*) malloc(sizeof(struct onode));
linkedlist ->data = (struct node*)malloc(sizeof(data)+1);
if(dataValue && data)
{
*dataValue = *data;
}
}
我对代码进行了更改,并添加了有关此功能所需内容的更多说明.一个变化:结构节点是结构顺序.
I have made changes in my code and added more description on what this function wants. one change : struct node is struct order.
struct order
{
int id;
char side;
int quantity;
double price;
};
struct onode
{
struct order* data;
struct onode* next;
struct onode* prev;
};
/**
* Returns a new linked list node filled in with the given order, The function
* allocates a new order and copy the values stored in data then allocate a
* linked list node. If you are implementing this function make sure that you
* duplicate, as the original data may be modified by the calling function.
*/
struct onode* newNode (struct order* data)
{
struct order* dataValue = (struct order*) malloc(sizeof(struct order));
struct onode* linkedlist = (struct onode*) malloc(sizeof(struct onode));
*dataValue = *data;
linkedlist ->data = dataValue;
linkedlist->data->id = dataValue->id;
linkedlist->data->price = dataValue->price;
linkedlist->data->quantity = dataValue->quantity;
linkedlist->data->side = dataValue->side;
linkedlist->next->prev = NULL;
return linkedlist;
}
推荐答案
问题的症结在于您正在创建两个新的 node
对象——一个是 dataValue
> 和一个是 linkedlist->data
.然后,当您确实希望将传入的数据存储在 linkedlist->data
中时,将其复制到 dataValue
中.
The crux of your problem is that you are creating two new node
objects--one that is dataValue
and one that is linkedlist->data
. You then copy the passed-in data into dataValue
when you really want it to be stored in linkedlist->data
.
如果更换
linkedlist ->data = (struct node*)malloc(sizeof(data)+1);
与
linkedList->data = dataValue;
这应该会让你朝着正确的方向前进.
that should get you moving in the right direction.
这篇关于复制链表 C 中的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!