为什么指针到指针在这个前卫被使用? [英] Why is pointer-to-pointer being used in this prog?
本文介绍了为什么指针到指针在这个前卫被使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面的程序展示了如何在C程序中建立一个二叉树。它采用动态内存分配,指针和递归。二叉树是一种非常有用的数据结构,因为它允许在排序列表中插入效率,检索和删除。作为这样的树基本上是一个递归定义的结构,递归编程处理它的自然和有效的方式。
The following program shows how to build a binary tree in a C program. It uses dynamic memory allocation, pointers and recursion. A binary tree is a very useful data-structure, since it allows efficient insertion, searching and deletion in a sorted list. As such a tree is essentially a recursively defined structure, recursive programming is the natural and efficient way to handle it.
tree
empty
node left-branch right-branch
left-branch
tree
right-branch
tree
这里的code:
Here's the code:
#include <stdlib.h>
#include <stdio.h>
struct tree_el {
int val;
struct tree_el * right, * left;
};
typedef struct tree_el node;
void insert(node ** tree, node * item) {
if(!(*tree)) {
*tree = item;
return;
}
if(item->val<(*tree)->val)
insert(&(*tree)->left, item);
else if(item->val>(*tree)->val)
insert(&(*tree)->right, item);
}
void printout(node * tree) {
if(tree->left) printout(tree->left);
printf("%d\n",tree->val);
if(tree->right) printout(tree->right);
}
void main() {
node * curr, * root;
int i;
root = NULL;
for(i=1;i<=10;i++) {
curr = (node *)malloc(sizeof(node));
curr->left = curr->right = NULL;
curr->val = rand();
insert(&root, curr);
}
printout(root);
}
为什么指针到指针使用呢?
Why is pointer-to-pointer used?
推荐答案
由于插入方法需要修改树的根。
Because the insert method needs to modify the root of the tree.
这篇关于为什么指针到指针在这个前卫被使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文