没有任何查书、没有任何上网查,全部纯手打,作为专业科思维训练。感觉非常有成就感!!!主要涉及单链表、双链表、链式队列、递归算法~
直接贴代码吧:
#include "stdio.h"
#include "stdlib.h"
struct childlist
{
struct node *current_node;
struct childlist *next;
};
struct node
{
int val;
struct node *parent;
struct childlist *child_list;
};
struct lian_dui
{
struct node *have_child_list_node;
struct lian_dui *next;
struct lian_dui *prev;
};
void create_sub_tree(struct node* p)
{
//子树链表和子树节点创建
int val =0,i=0,cmd=0;
struct childlist *childlisttemp = p->child_list;
while(val!=-1)
{
printf("child %d val in the node:",i);
scanf("%d",&val);
childlisttemp->current_node = (struct node*)malloc(sizeof(struct node));
childlisttemp->current_node->val = val;
printf("if you want to add node to this node,press 1 and enter now:");
scanf("%d",&cmd);
if(cmd==1)
{
childlisttemp->current_node->child_list = (struct childlist*)malloc(sizeof(struct childlist));
create_sub_tree(childlisttemp->current_node);
}
else
{
childlisttemp->current_node->child_list = NULL;
}
childlisttemp->next = (struct childlist*)malloc(sizeof(struct childlist));
childlisttemp->current_node->parent = p;
childlisttemp = childlisttemp->next;
i++;
}
i = 0;
}
struct node* create_tree(struct node* p)
{
struct node *head = p;
int val,i=0,cmd=0;
//头节点:
printf("input the val of head:\n");
scanf("%d",&val);
head->val = val;
head->child_list = (struct childlist*)malloc(sizeof(struct childlist));
create_sub_tree(head);
return head;
}
void read_tree(struct childlist *p)
{
struct childlist *temp = p;
struct node *temp_tree_node;
struct lian_dui *array,*array_head,*array_rear;
if(temp!=NULL)
{
array = (struct lian_dui*)malloc(sizeof(struct lian_dui));
array->next = NULL; array->prev = NULL; array->have_child_list_node = NULL;
array_head = array;
array_rear = array;
while(temp->current_node->val!=-1)
{
printf("%d\n",temp->current_node->val);
if(temp->current_node->child_list!=NULL)
{
array_rear->have_child_list_node = temp->current_node; //有子树链表的节点入队
//printf("正在入队\n");
array_rear->next = (struct lian_dui*)malloc(sizeof(struct lian_dui));
array_rear->next->next = NULL; array_rear->next->prev = NULL; array_rear->next->have_child_list_node = NULL;
array_rear->next->prev = array_rear;
array_rear = array_rear->next; //最后一个子树链表的节点入队后会有一个have_child_list_node值为空的节点在队尾
}
temp = temp->next;
}
//当前层遍历结束,遍历下一层,也就是出队了
temp_tree_node = array_head->have_child_list_node;
while(temp_tree_node!=NULL)
{
read_tree(temp_tree_node->child_list);
array_head = array_head->next;
temp_tree_node = array_head->have_child_list_node;
free(array_head->prev);
}
}
}
main()
{
struct node *head = (struct node*)malloc(sizeof(struct node));
struct node *tree = create_tree(head);
printf("%d\n",tree->val); //先输出头节点
read_tree(tree->child_list); //再从第二层(头节点的子树)开始遍历
}
/*******************************************************************************************************************************************************************/
运行效果:
输入:
输出:
贴上自己的思考过程: