我试图从双循环链表中弹出最后一个节点,但指针让我头疼。我有一个函数,它遍历整个列表直到它的末尾,但不知何故,tmp指针不会移动或更新。我用for循环而不是while循环遍历整个列表,因为它对我来说更舒服(是的,我尝试过while循环(
这是我的代码:
typedef struct List {
unsigned int size;
Node *p_head;
Node *p_tail;
} List;
typedef struct Node {
void *p_value;
struct Node *p_next;
struct Node *p_previous;
} Node;
Bool RemoveAtEnd(List *list) {
Node *p_node = list->p_head; /* tmp ptr */
for (int i = 0; i < GetSize(list); ++i) {
p_node = (p_node)->p_next;
}
/*
* p_node var should be the last node or tail of the list shouldn't it?
*/
printf("Tail here is %dn", *(int *) p_node->p_value);
list->p_tail = p_node->p_previous;
list->p_tail->p_next = list->p_head;
list->p_head->p_previous = list->p_tail;
list->size--;
DestroyNode(p_node);
return TRUE;
}
当试图在函数valgrind中释放节点时;无效读取";当试图遍历函数外的列表时,因为据我所见,尾部指向头部而不是尾部
List *p_intList = CreateList();
for (int i = 0; i < 5; ++i) {
int a = i + 1;
InsertAtEnd(p_intList, &a, sizeof(int));
}
RemoveAtEnd(p_intList);
for (int i = 0; i < GetSize(p_intList); ++i) {
printf("%dn", *(int *) GetValueAt(p_intList, i)); // Invalid read
}
DestroyList(p_intList);```
在伪代码中,我喜欢这个
你知道last-1 -> last -> head
,你需要的是列表
变成last-1 > head
-
保存最后一个节点
last = list.getHead()->prev;
-
带有节点头的最后一个链接
last-1 = list.getHead()->prev->prev;
last-1.next = list.getHead();
list.getHead().prev = last-1
-
免费删除节点
free(last);