0

我想实现拆分函数来学习 C 硬方式双链表,但要做到这一点,我需要每个节点都将其索引号作为常规列表,数组有。当我执行将新节点添加到列表末尾的“推送”功能时,一切都很好,但是当我执行将节点添加到列表顶部的“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;
}
4

1 回答 1

0

"cur" 是 for 循环中的不变量

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

并且,"for(i = 0;i < list->count -1" 是一个 'off by one'。假设 list->count 等于 1,list->count-1 是 "0" 并且 "for(i = 0; i < 0;i++)" 什么都不做

于 2013-10-17T15:31:37.590 回答