0
我想實現拆分功能來學習C困難的方式雙鏈表,但要做到這一點,我需要每個節點都有他們的索引號作爲常規列表,數組都有。當我執行'推'功能,它將新節點添加到列表的末尾時,一切都很好,但是當我執行「不移位」時,將節點添加到列表頂部時,我遇到了使每個節點保持適當索引的問題編號從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;
}
是的,你是對的,但即使我我試圖在循環中使用這個條件,但這個函數的最終結果是錯誤的。你能給我一些提示,以幫助處理這個問題嗎? –