【问题标题】:Data Structre of Stack in CC中栈的数据结构
【发布时间】:2016-12-28 11:36:33
【问题描述】:

我是结构的新手,我试图实现一个堆栈以及将数据推入堆栈并打印它们的操作。但是,我遇到了一些问题,请您帮我解决一下吗?

我使用了教程点提供的编译器,其中代码编译成功,但输出包含分段错误,我认为它存在于“PushNode”或“PrintStackData”中。

当我输出堆栈中的节点数(使用计数器)时,这个数字比正确的多一个,比如我输入了 5 个数据,但它打印出 6 个。

非常感谢!

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



//Define data node
typedef struct Node{
    int data; //Data of data node in Stack
    struct Node *Next;  // Pointer pointing to next data node or null
}NODE;

//Define head node for stack
typedef struct StackHead{
    int Counter;
    NODE *Top;
}STACKHEAD;

// function to create a blank stack
void CreateStack(STACKHEAD *Head){      
    Head= (STACKHEAD*)malloc(sizeof(STACKHEAD));
    Head->Counter=0;
    Head->Top = NULL;   
};

//Function to push a data node in stack
void PushNode(STACKHEAD *Head){

    NODE *pNew=(NODE*)malloc(sizeof(NODE)); //Must allocate memory to initialise it otherwise segmentation error.
    printf("Enter value for new data Node: ");
    scanf("%d",&(pNew->data));  //Assign input to data of new node

    if(Head->Top==NULL){
        pNew->Next=NULL;
    }
    else{
        pNew->Next=Head->Top;
    }
    Head->Top=pNew;
    Head->Counter++;
};

//Function to print out each data node in the Stack
void PrintStackData(STACKHEAD *Head){

    STACKHEAD *Position=(STACKHEAD*)malloc(sizeof(STACKHEAD));

    //Position->Top=Head->Top;
    Position = Head;

    printf("The data in the Stack is: ");
     while(Position->Top!=NULL){
         printf("%d, ",Position->Top->data);
         Position->Top= Position->Top->Next;
    }
}

int main()
{
    int numOfData; // Number of data that users want to insert into the stack
    STACKHEAD *Head; //Declare and initialise a new Stack Head
    CreateStack(Head); // Initialise the Stack

    printf("How many data do you want to insert to the Stack?");
    scanf("%d", &numOfData);

    for(int i=0;i<numOfData;i++){
        PushNode(Head);
    }
    printf("The data value of the top Node is %d\n", Head->Top->data);

    PrintStackData(Head);   //print out each data node in Stack using function.

    printf("\nThe number of data in the Stack is: %d\t", Head->Counter); 

    printf("\nThe data value of the top Node is %d\t", Head->Top->data);
    getchar();

}

【问题讨论】:

  • 搜索并阅读关于在 c 中模拟传递引用。或者如何从函数中返回值。
  • “请调试我的代码”问题不在主题范围内/不允许。
  • 你从未初始化过Head。在CreateStack 函数内分配给Head 不会修改调用者的变量。
  • CreateStack 应该返回分配的结构,而不是将其作为参数。
  • 顺便说一下,您的PrintStackData 函数包含内存泄漏。 并且在您重写堆栈时出现了一个非常糟糕的逻辑错误(并导致更多的内存泄漏)。

标签: c data-structures stack


【解决方案1】:

当你调用 CreateStack 时,指针是按值传递的。函数中调用 malloc 返回的指针永远不会分配给堆栈头。

尝试编写一个 CreateStack 函数,该函数返回一个指向所创建堆栈的指针。它不应该带任何参数。

【讨论】:

  • 谢谢你,克里斯,我会试试的。也感谢大家,你们让我进步了:)
猜你喜欢
  • 2015-10-21
  • 2021-05-29
  • 1970-01-01
  • 2020-04-20
  • 2014-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多