我正在尝试复制链表中的节点。我不确定我是否做得正确。我尝试制作测试用例,但没有成功。如果有人可以告诉我哪里出了问题以及我做对了什么,以及测试我的代码的最佳方法是什么。
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;
}
}
我对代码进行了更改,并添加了有关此函数所需内容的更多描述。
一项更改:结构节点是结构顺序。
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
。然后将传入的数据复制到dataValue
当您确实希望将其存储在linkedlist->data
.
如果你更换
linkedlist ->data = (struct node*)malloc(sizeof(data)+1);
with
linkedList->data = dataValue;
这应该会让你朝着正确的方向前进。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)