我一直試圖解決這個問題,但我無法完成它。它是一個鏈表(只有next或down,多級鏈表),每個節點都可以有孩子,如下圖:
1c -> 3 -> 5c -> 7
| |
2 4
|
9
為了展平串列,所有子節點必須按順序移動到其父節點的右側。這應該是結果:
“名單:1 2 3 5 4 9 7”
我已嘗試使用此代碼,但我不明白如何對 create_list 函式產生影響,然后將其與更改一起列印。
到目前為止,這是我的代碼:
#include <stdio.h>
#include <stdlib.h>
//Flatten linked list problem
typedef struct node
{
int data;
struct node *next;
struct node *down;
}node;
node node1, node2, node3, node4, node5, node6, node7;
node *head;
void create_list()
{
node1.data = 1; node1.down = &node5; node1.next = &node2;
node2.data = 3; node2.down = NULL; node2.next = &node3;
node3.data = 5; node3.down = &node7; node3.next = &node4;
node4.data = 7; node4.down = NULL; node4.next = NULL;
node5.data = 2; node5.down = NULL; node5.next = NULL;
node6.data = 5; node6.down = &node7; node6.next = NULL;
node7.data = 0; node7.down = NULL; node7.next = NULL;
head = &node1;
}
void print(node *header)
{
node * temp = header;
printf("List : ");
while(temp != NULL)
{
printf("%d%s ", temp->data, (temp->down) ? "c":""); //c = has a child
temp = temp->next;
}
printf("\n");
}
void expand(node *h)
{
/*
node *ptr = h, *temp_next, *n;
while (ptr)
{
if(ptr->down)
{
temp_next = ptr->next;
ptr->next = ptr->down;
ptr->next = ptr;
ptr->down = NULL;
n = ptr->next;
while (n->next) n = n->next;
n->next = temp_next;
if(n->next) n->next= n;
}
ptr = ptr->next;
}
*/
}
int main()
{
create_list();
printf("Before: \n");
print(head);
//Flatten the list
expand(head);
printf("After: \n");
print(head);
}
uj5u.com熱心網友回復:
這個回圈逐個節點移動通過down指標連接的所有節點到next指標,同時保留串列的順序。
for(node *pt = head; pt != NULL; pt = pt->next)
if(pt->down){
pt->down->next = pt->next;
pt->next = pt->down;
pt->down = NULL;
}
如果此解決方案的邏輯不清楚,則可能值得閱讀指標以及鏈表、二叉樹和其他相關資料結構
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/518347.html
標籤:C
上一篇:c、不能列印字串中的字符
下一篇:用于讀取這些命令列引數的偽代碼?
