スタックオーバーフローの可能性を回避する場合は、キューを追加することで反復の代わりに繰り返しを使用することができます。—これは少しヒープメモリを使用しますが、実行する可能性があります大きなリストを持っている場合や、メモリが制約されているシステムで実行している場合は、ヒープメモリを使用してください。重要な部分は最後にprint_list
関数です。他のものは、私が提供してきましたちょうど(主に)自己管理キューの実装です:
typedef struct node_queue NodeQueue;
struct node_queue {
NODE *n;
NodeQueue *next;
};
/*
* Add an item to the end of the queue.
*
* If the item could not be added, 0 is returned.
* Otherwise, a nonzero value is returned.
*/
int enqueue(NodeQueue **headp, NodeQueue **endp, NODE *n)
{
NodeQueue *old_end = *endp;
NodeQueue *new_end;
new_end = malloc(sizeof *new_end);
if (new_end == NULL) {
return 0;
}
new_end->n = n;
new_end->next = NULL;
if (old_end != NULL) {
old_end->next = new_end;
}
if (*headp == NULL) {
*headp = new_end;
}
*endp = new_end;
return 1;
}
/*
* Remove an item from the head of the queue,
* storing it in the object that "nret" points to.
*
* If no item is in the queue, 0 is returned.
* Otherwise, a nonzero value is returned.
*/
int dequeue(NodeQueue **headp, NodeQueue **endp, NODE **nret)
{
NodeQueue *old_head = *headp;
NodeQueue *new_head;
if (old_head == NULL) {
return 0;
}
if (nret != NULL) {
*nret = old_head->n;
}
new_head = old_head->next;
free(old_head);
if (new_head == NULL) {
*endp = NULL;
}
*headp = new_head;
return 1;
}
void print_list(NODE *start)
{
NodeQueue *head = NULL;
NodeQueue *end = NULL;
NODE *current;
current = start;
/* Iterate all `pNext` nodes, then pop each `pDown` node and repeat. */
for (;;) {
/* Add the "down" node to the node queue. */
if (current->pDown != NULL) {
if (!enqueue(&head, &end, current->pDown)) {
perror("warning: could not add node to queue");
}
}
printf("%s", current->pszNode);
/*
* Move to the "next" node.
* If there is no next node, get the first "down" node from the queue.
* If there is no "down" node, break the loop to end processing.
*/
current = current->pNext;
if (current == NULL) {
if (!dequeue(&head, &end, ¤t)) {
break;
}
}
}
}
これはpDown
項目に移動する前に、すべてのpNext
の項目を反復処理します。次の2-DリストはA B C D E F G H I J K L M N O P Q
として印刷される。
A
|
B--C
|
D--E-----------F
| |
G-----H I-----J
| | | |
K--L M--N O P
|
Q
あなたはその内部pNext
とpDown
を交換することにより、print_list
関数でpDown
/pNext
の優先順位を逆にすることができ、そうpNext
アイテムをキューとpDown
に追加されます項目がリストの構造を変更しない限り、アイテムがA B D C E G K F I O H M Q L J P N
に印刷される順序が変更される、疲れまで反復されます。
上記のコードと上記の最初の2-Dリンクリストの例をhttps://repl.it/NjyV/1で見ることができますが、NODE
の定義を変更して、フィールドを少し単純にするようにしています。
再帰再帰を参照してください。 –
もちろん、ありがとうございます。 – Hi7651
「pHead-> pNext-> pNext-> pszName'のようなことはできませんか?このようなループや簡単なステートメントを使用して、深いところまで行くことができます。あなたが求めているのはこれですか? – ThisSiteSucks