gpt4 book ai didi

c - 双链表 - 无法编写为节点提供正确索引号的迭代器

转载 作者:行者123 更新时间:2023-11-30 17:46:08 26 4
gpt4 key购买 nike

我想实现 Split 函数来学习 C 的困难方式双链表,但要做到这一点,我需要每个节点都有其索引号,就像常规列表、数组一样。当我执行“Push”功能(将新节点添加到列表末尾)时,一切都很好,但是当我执行“Unshift”(将节点添加到列表顶部)时,我在保持每个节点正确的索引方面遇到了问题从 0 开始的数字。我想在函数的末尾创建一个迭代器,它遍历每个节点并给出第一个 0,第二个 1 .. 等等。到目前为止我所做的是,每个节点索引都被更改为0而不增加它。希望大家能帮我解决这个问题。

 'list.h'    
#ifndef lcthw_List_h
#define lcthw_List_h

#include <stdlib.h>

struct ListNode;

// ListNode contains value, next, and prev struct. Each ListNode is another
// chain in structure, they are linked
typedef struct ListNode {
struct ListNode *next;
struct ListNode *prev;
void *value;
int track_num;
} ListNode;

// List is an guardian angel of ListNodes, it keeps tracking them by count
// and knows which Node is first and last
typedef struct List {
int count;
ListNode *first;
ListNode *last;
} List;


// Some standard functions for operate lists
List *List_create();
void List_destroy(List *list);
void List_clear(List *list);
void List_clear_destroy(List *list);

// These Macros return count, first and last element of the list
#define List_count(A) ((A)->count)
#define List_first(A) ((A)->first != NULL ? (A)->first->value : NULL)
#define List_last(A) ((A)->last != NULL ? (A)->last->value : NULL)

// List_push adds a new element to the end of the list
void List_push(List *list, void *value);
//List_pop takes the last element of the list and returns it
void *List_pop(List *list);

// Unshift adds element to the top of the list
void List_unshift(List *list, void *value);
// Shift retuns and remove first element from the list
void *List_shift(List *list);

// Removes list
void *List_remove(List *list, ListNode *node);

// This Macro is very useful, It Iterates through elements in the list
#define LIST_FOREACH(L, S, M, V) ListNode *_node = NULL;\
ListNode *V = NULL;\
for(V = _node = L->S; _node != NULL; V = _node = _node->M)

#endif


'list.c sample with subject function'
void List_unshift(List *list, void *value)
{
int i;
assert(list != NULL);
assert(list->count >= 0);
if(list->count > 0) {
assert(list->first != NULL);
}

ListNode *node = calloc(1, sizeof(ListNode));
check_mem(node);

node->value = value;

if(list->first == NULL) {
list->first = node;
list->last = node;


} else {
node->next = list->first;
list->first->prev = node;
list->first = node;


}

list->count++;

LIST_FOREACH(list, first, next, cur) {
for(i = 0;i < list->count -1;i++) {
cur->track_num = i;
}
}
error:
return;
}

最佳答案

“cur”是 for 循环内的不变量

for(i = 0;i < list->count -1;i++) {
cur->track_num = i;
}

并且,“for(i = 0;i < list->count -1”是“减一”。假设 list->count 等于 1,list->count-1 是“0”并且“for (i = 0; i < 0;i++)"不执行任何操作

关于c - 双链表 - 无法编写为节点提供正确索引号的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19430741/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com