【发布时间】:2013-03-10 22:44:09
【问题描述】:
我正在尝试复制链表中的节点。我不确定我是否做得正确。我尝试制作测试用例,但没有成功。如果有人能告诉我我哪里出了问题以及我做对了什么,那么测试我的代码的最佳方法是什么。
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;
}
【问题讨论】:
-
你的测试用例是什么?结果如何?
-
我的测试用例从未编译过。所以我删除它来检查。我想我不确定如何制作一个关于它的测试用例。我所做的是创建一个名为 newnode 的新节点(将成为数据节点)并传递我创建的节点。
-
您不需要在 C 程序中强制转换
malloc的返回值。 -
什么是“结构顺序”?
-
@Eciliptus:一定要给你的教授this link,这样他就可以看到他要求你这样做是多么愚蠢。
标签: c linked-list