【发布时间】:2015-01-25 18:07:51
【问题描述】:
我有一个完整的链表,里面有数据,我想要的是用相同的数据填充另一个链表,但有一个条件,所以假设这是链表:
char cl;
int time;
int lng;
C 0 1
D 0 2
B 2 1
A 2 2
我想从这个列表复制到一个新的空列表,但前提是(时间>0),所以新的将是这样的:
B 2 1
A 2 2
我试过这段代码,但它不起作用:
void insert(const node * n )// this where i put the pointer of the full node
{
node *head=n;
node *sec; // new node
sec=(node*)malloc(sizeof(node));
do{
if(head->time>0){
strcpy(sec->cl,head->cl);
sec->time= head->time;
sec->lng= head->lng;
head=head->next;
sec=sec->next;
}
else
head=head->next;
}while(head!=NULL);
print(sec) // this will print the new node
}
请帮帮我。谢谢
【问题讨论】:
-
'new'是c++中的保留字,如果编译器既懂C又懂C++,就会出问题。
-
你是如何创建原始链表的?为什么你不能使用你用来构建该列表的函数?
-
您只为
sec中的第一项而不是后续的分配内存,sec=sec->next将导致未定义的行为,因为该字段尚未初始化。 -
删除
else head=head->next;之前的else -
while(head!=NULL)应该在循环的顶部,而不是尾部。
标签: c list linked-list