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

时间:2013-10-17 15:20:08

标签: c list loops iteration

我想实现Split函数来学习C Hard Way Double Linked List但是为了做到这一点,我需要每个节点将它们的索引号作为常规列表,数组具有。当我执行“推送”功能,它将新节点添加到列表的末尾时,一切都很好,但是当我执行“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;
}

1 个答案:

答案 0 :(得分:0)

“cur”是for循环中的一个不变量

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

和,“for(i = 0; i&lt; list-&gt; count -1”是'off by one'。Say list-&gt; count等于1,list-&gt; count-1是“0 “和”for(i = 0; i&lt; 0; i ++)“什么都不做