我按照您的要求實施鏈接列表。希望這會幫助你。在這個鏈接列表中,節點內的每個指針指向下一個節點指針。
請在你的程序stdio.h中,memory.h的頂部添加這3頭文件和STDLIB.H這一計劃的
struct Node {
int val;
void *next;
};
void main(void)
{
typedef struct Node NODE;
NODE *f,*p,*q = NULL;
int i = 1;
/* First create your first node here */
f = (NODE *)malloc(sizeof(NODE));
f->next = f;
f->val = 0;
p = f;
/* now lets create link list with 10 nodes */
while(i < 10)
{
q = (NODE *)malloc(sizeof(NODE));
q->next = q;
q->val = i++;
p->next = q->next; /* first node is pointing to the next node pointer */
p = q;
}
/* search the link list and print its value */
p = f; /* now p is pointing to the first node of the link list */
i = 0;
/* first print the value of first node here */
printf("Node :%d and val = %d\n", i, p->val);
while(p->next != p)
{
printf("Node :%d and val = %d\n", i++, ((NODE *)(p->next))->val);
p = p->next;
}
}
輸出;
節點:0和val = 0
節點:1和val = 1
節點:2和val = 2
節點:3和val = 3
節點: 4和val = 4
節點:5和val = 5
節點:6和val = 6
節點:7和val = 7
節點:8和val = 8
節點:9和Val = 9
爲什麼你有這樣的限制?爲什麼你將它聲明爲'void *'而不是'struct node **'? – Barmar
'next'指針從結構開始就是某個[* offset *](http://en.cppreference.com/w/c/types/offsetof)。儘管非常沮喪,但您可以通過一些簡單的算法獲得指向結構的指針。 –
這是一個學校作業,我們不能修改結構。我們必須編寫一個與這樣的列表一起工作的函數,但我需要了解列表的工作方式,然後才能做到這一點。我找不到像這樣的列表的任何例子。限制在這個賦值中,void * next指向下一個節點中的下一個字段,而不是節點的開始。也就是說,curr_node.ptr =&(next_node.ptr);不curr_node.ptr =&next_node – Avallauch