I have the following structure for my linked list.
我的链表有以下结构。
typedef struct value value;
struct value{
value* prev;
value* next;
int value;
};
...
//ent = entry
if(entry_head == NULL) {
entry_head = ent;
entry_tail = ent;
entry_tail->prev = NULL;
}
else { // add to top
ent -> next = entry_head;
ent -> prev = NULL;
entry_head -> prev = ent;
entry_head = ent;
}
This gives me the results:
这给了我结果:
Input: a Result: b
b a
However when I input two of the same variables, I want to delete the previous variable and have the newly input variable only. ie.
但是,当我输入两个相同的变量时,我想删除前一个变量并仅使用新输入的变量。即。
Input: a // old Result: a // new Actual Result: a // new
a // new a // old
How do I modify this so that It removes the older variable?
如何修改它以便删除旧变量?
1 个解决方案
#1
You need to modify the add node code, in the part of the function that deals with all nodes added to a non NULL list.
您需要在处理添加到非NULL列表中的所有节点的函数部分中修改添加节点代码。
value *tmp =head ;
while(tmp!=NULL) {
if(tmp->Value== newval) break;
tmp=tmp->next;
}
If(tmp!=NULL) return 0;
// add node here
return 1
Alternatively after adding a node, create a similar while loop.
或者,在添加节点之后,创建类似的while循环。
For every node in the list all nodes after this have to be compared and removed. This will be in efficient.
对于列表中的每个节点,必须比较和删除此后的所有节点。这将是有效的。
To remove a node all you do is some pointer twizzling , then free the node if no longer needed to avoid memory leaks
要删除一个节点,你所做的只是一些指针闪烁,然后释放节点,如果不再需要避免内存泄漏
// a->B->c
// <- <-
value *save=a->next;
a->Next=save->next;
// node c
Save->Next->prev=save->prev;
free(save);
This code hasn't been tested, I have no linux on my phone.
这段代码还没有经过测试,我手机上没有linux。
#1
You need to modify the add node code, in the part of the function that deals with all nodes added to a non NULL list.
您需要在处理添加到非NULL列表中的所有节点的函数部分中修改添加节点代码。
value *tmp =head ;
while(tmp!=NULL) {
if(tmp->Value== newval) break;
tmp=tmp->next;
}
If(tmp!=NULL) return 0;
// add node here
return 1
Alternatively after adding a node, create a similar while loop.
或者,在添加节点之后,创建类似的while循环。
For every node in the list all nodes after this have to be compared and removed. This will be in efficient.
对于列表中的每个节点,必须比较和删除此后的所有节点。这将是有效的。
To remove a node all you do is some pointer twizzling , then free the node if no longer needed to avoid memory leaks
要删除一个节点,你所做的只是一些指针闪烁,然后释放节点,如果不再需要避免内存泄漏
// a->B->c
// <- <-
value *save=a->next;
a->Next=save->next;
// node c
Save->Next->prev=save->prev;
free(save);
This code hasn't been tested, I have no linux on my phone.
这段代码还没有经过测试,我手机上没有linux。