帶雙親的孩子連結串列
#include<iostream>
#include<malloc.h> using namespace std; typedef char TElemType; #define max 100 typedef struct Child { int data; struct Child* next; }*Tchild,Child;
typedef struct { int parent; TElemType data; Tchild firstchild; }Jiedian;
typedef struct { Jiedian node[max]; int n, r; }PTree;
void InitTree(PTree &tree) { tree.n = 0; tree.r = 0; }
void CreateTree(PTree &tree) { int count, i, j, k; int child; Tchild childhead = NULL, childptr = NULL, childtemp = NULL; cout << "請輸入樹節點的總數" << endl; cin >> count; tree.n = count; if (0 == count) { tree.n = 0; return; } else { for (i = 0; i < count; i++) { cout << "請輸入第" << i << "節點的值" << endl; cin >> tree.node[i].data; cout << "請輸入它的雙親的序號" << endl; cin >> tree.node[i].parent; cout << "請輸入它的孩子的數目" << endl; cin >> j; if (0 == j) { tree.node[i].firstchild = NULL; continue; } else { childhead = (Tchild)malloc(sizeof(Child)); cout << "請輸入第個孩子的序號的值" << endl; cin >> child; childhead->data = child; childhead->next = NULL; childptr = childhead; if (j - 1 == 0) { tree.node[i].firstchild = childhead; continue; } else { for (k = 0; k < j - 1; k++) { cout << "請輸入第" << k + 2 << "個孩子的序號" << endl; cin >> child; childtemp = (Tchild)malloc(sizeof(Child)); childtemp->data = child; childtemp->next = NULL; childptr->next = childtemp; childptr = childtemp; } tree.node[i].firstchild = childhead; } } } } }
void FindChild(PTree tree) { TElemType ch; Tchild ptr = NULL; cout << "請輸入你想要查詢樹的值" << endl; cin >> ch; for (int i = 0; i < tree.n; i++) { if (ch == tree.node[i].data)//找雙親 { cout << ch << "的雙親的序號為:" << tree.node[i].parent << endl; cout << "它的雙親的值為:" << tree.node[tree.node[i].parent].data << endl; ptr = tree.node[i].firstchild; if (NULL == ptr) break; else { int i = 1; while (ptr!= NULL) { cout << "它的第" << i << "個孩子的值為" << tree.node[ptr->data].data << endl; i++; ptr = ptr->next; } } }
}
}
int main() { PTree tree; InitTree(tree); CreateTree(tree); FindChild(tree); return 0; }