BST,后继者,代码问题

BST, successor, code issue

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

编译器运行它启动的程序并在几秒钟后结束。我认为这是 'segmentation fault' 类型的错误(我使用的是 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. 时更新下一个节点
  3. 您正在将一个整数传递给 ReversePrint(),它需要一个 struct Node 指针,这会导致分段错误。

  4. 您永远不会释放节点。我没有添加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