C中堆栈的数据结构

时间:2016-08-22 02:43:18

标签: c data-structures stack

我是新手来构建并尝试实现堆栈以及在堆栈中推送数据并打印它们的操作。但是,我遇到了一些问题,你能帮帮我吗?

我使用了教程点提供的编译器,其中代码编译成功,但输出包含一个分段错误,我假设它存在于' PushNode'或者' PrintStackData'。

当我输出堆栈中的节点数(使用Counter)时,该数字比正确的数字多一个,比如我输入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();

}

1 个答案:

答案 0 :(得分:1)

当您调用CreateStack时,指针将按值传递。函数中对malloc的调用返回的指针永远不会分配给STACKHEAD。

尝试编写一个CreateStack函数,该函数返回指向创建的堆栈的指针。它不应该采取任何论据。