我一直致力于二元搜索树及其几个功能实现,用于学校作业。我刚刚写了我的广度优先搜索功能,我在queueenter函数的else语句中遇到了分段错误。
任何人都可以指点我需要做些什么才能完善我的实施?
以下是代码:
/*This code will implement a binary search tree based on 20
user-inputed integers. It will then implement a search,
insert, delete, and traverse function. */
#include <stdio.h>
#include <stdlib.h>
#define ARRSIZE 20
/*------ TYPE DEFINITIONS ------*/
typedef struct node
{
int data;
struct node* left;
struct node* right;
struct node* next;
} node;
typedef struct tree
{
int count;
struct node* root;
} tree;
typedef struct queue
{
int count;
struct node* front;
struct node* rear;
} queue;
/*------ FUNCTION DECLARTATIONS ------*/
void InitializeTree (tree* ptree);
int insert (int data, tree* ptree);
void place (node* root, node* new_node);
void BreadthFirst (tree* ptree);
node* queuedelete (queue* pq);
void queueenter (queue* pq, node* pn);
int queueisempty(queue* pq);
/*------ MAIN FUNCTION ------*/
int main (void)
{
int i, arr[ARRSIZE];
tree BST;
InitializeTree(&BST);
printf("Enter 20 integers for a list.\n");
for(i=0; i<ARRSIZE; i++)
{
printf("Integer %d:\n", i+1);
scanf("%d", &arr[i]);
if(insert(arr[i], &BST) == 0)
{
printf("Error in creating node.\n");
exit(1);
}
}
BreadthFirst(&BST);
return 0;
}
/*
* ADDITIONAL FUNCTIONS
*
*/
/*------ CREATION FUNCTIONS ------*/
void InitializeTree (tree* ptree)
{
ptree->count = 0;
ptree->root = NULL;
}
int insert (int data, tree* ptree)
{
node* new_node;
new_node = (node*) malloc(sizeof(node));
if(new_node == NULL)
{
printf("Couldn't create a node.\n");
return 0;
}
new_node->data = data;
ptree->count++;
if(ptree->root == NULL)
{
ptree->root = new_node;
}
else
{
place(ptree->root, new_node);
}
return 1;
}
void place (node* root, node* new_node)
{
if(new_node->data < root->data)
{
if(root->left == NULL)
{
root->left = new_node;
}
else
{
place(root->left, new_node);
}
}
else
{
if(root->right == NULL)
{
root->right = new_node;
}
else
{
place(root->right, new_node);
}
}
}
/*------ TRAVERSAL FUNCTIONS ------*/
void BreadthFirst (tree* ptree)
{
static int i;
queue buff;
node* temp;
if(ptree->root == NULL)
{
return;
}
queueenter(&buff, ptree->root);
while(!queueisempty(&buff))
{
temp = queuedelete(&buff);
printf("Node% - %d\n", i++, temp->data);
if(temp->left != NULL)
{
queueenter(&buff, temp->left);
}
if(temp->right != NULL)
{
queueenter(&buff, temp->right);
}
}
free(&buff);
}
node* queuedelete (queue* pq)
{
if(queueisempty(pq))
{
return NULL;
}
pq->front = pq->front->next;
pq->count--;
if(queueisempty(pq))
{
pq->rear = NULL;
return NULL;
}
return pq->front;
}
void queueenter (queue* pq, node* pn)
{
node* temp;
if(queueisempty(pq))
{
pq->front = pn;
}
else
{
pq->rear->next = pn;
}
pq->rear = pn;
pq->count++;
}
int queueisempty(queue* pq)
{
return pq->count == 0;
}
提前感谢您的帮助和耐心!
答案 0 :(得分:1)
第一次通过该功能,你设置了pq-&gt; front,但你保留了pq-&gt;后面未初始化。第二次,你取消引用pq-&gt;后面的段,因为它有一个随机值。