gpt4 book ai didi

c - BST、后继者、代码问题

转载 作者:行者123 更新时间:2023-11-30 19:44:28 26 4
gpt4 key购买 nike

我了解BST中后继者的一般概念。我的代码仍然有问题,我不明白问题出在哪里。

编译器运行它启动的程序并在几秒钟后结束。我认为这是“段错误”类型的错误(我使用的是 Windows 和 Dev C++)。

 #include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* next;
};

struct Node* head;

struct Node* GetNewNode(int x){
struct Node* newNode= (struct Node*)malloc(sizeof(struct Node));
newNode->data = x;
newNode->next =NULL;
return newNode;
}

void InsertAtHead(int x){
struct Node* newNode = GetNewNode(x);
if(head==NULL){
head=newNode;
return;}
newNode->next=head;
head=newNode;
}

void Print(){
struct Node* temp=head;
printf("forward:");
while(temp!=NULL){
printf("%d", temp->data);
temp = temp->next;
}
printf("\n");
}

void ReversePrint(struct Node* p){
if(p==NULL){
return;
}
ReversePrint(p->next);
printf("%d",p->data);
}

int main(void){
head=NULL;
InsertAtHead(2); Print(); ReversePrint(2);
InsertAtHead(4); Print(); ReversePrint(4);
InsertAtHead(6); Print(); ReversePrint(6);

}

最佳答案

您的代码有一些错误需要提及

  1. 您总是在 InsertAtHead() 函数中重新分配 head。您应该保留对列表尾部的引用,并在每次调用 InsertAtHead() 时更新下一个节点。

  2. 您正在向 ReversePrint() 传递一个整数,该整数需要一个 struct Node 指针,这会导致段错误。

    <
  3. 您永远不会释放节点。我没有添加 FreeNodes() 函数,您应该很容易实现。

这是您的代码的更正版本,希望它可以帮助您查看错误

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next;
};

struct Node* head;
struct Node* tail;

struct Node* GetNewNode(int x) {
struct Node* newNode = malloc(sizeof(struct Node));

if (newNode == NULL)
return NULL;
newNode->data = x;
newNode->next = NULL;

return newNode;
}

void InsertAtHead(int x) {
struct Node* newNode = GetNewNode(x);
if (head == NULL) {
head = newNode;
tail = head;
return;
}
if (tail != NULL)
tail->next = newNode;
tail = newNode;
}

void Print(){
struct Node* current = head;

printf("forward:\n");
while (current != NULL) {
printf("\t%d\n", current->data);
current = current->next;
}
printf("\n");
}

void ReversePrint(struct Node *node) {
if (node == NULL) {
return;
}
ReversePrint(node->next);
printf("%d\n", node->data);
}

int main(void) {
InsertAtHead(2);
InsertAtHead(4);
InsertAtHead(6);

Print();
ReversePrint(head);

return 0;
}

您不需要将全局变量显式初始化为 0NULL

关于c - BST、后继者、代码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28118958/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com