C语言实现栈的问题

查看:116
本文介绍了C语言实现栈的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

为什么代码没有正常输出?

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

int main()
{
    Stack S;
    int isEmpty;
    printf("##########栈操作########\n");
    S = CreateStack();
    printf("输出栈中元素\n");
    return 0;
}

下面是stack.h代码

#ifndef _STACK_H
#define _STACK_H
typedef int ElementType;

struct StackNode;
typedef struct StackNode *PtrToStackNode;
typedef PtrToStackNode Stack;

int IsEmpty( Stack S );
Stack CreateStack( void );
void DisposeStack( Stack S );
void MakeEmpty( Stack S );
void Push( ElementType E, Stack S );
ElementType Top( Stack S );
void Pop( Stack S );
/*实现栈---带特殊头结点的链表*/
struct StackNode
{
    ElementType Element;
    PtrToStackNode Next;
};

#endif //LINKEDLIST_STACK_H

int IsEmpty( Stack S )
{
    return S->Next == NULL;
}

Stack CreateStack( void )
{
    Stack S;
    printf("What do you echo?\n");

    S = malloc( sizeof( struct StackNode ) );
    if( S == NULL )
        exit(1);
    MakeEmpty( S );
    printf("\nIs something wrong here?\n");
    return S;
}

void MakeEmpty( Stack S )
{
    printf("\nMakeEmpty Stack\n");
    int tmp;
    if( S == NULL )
    {
        printf("S == NULL\n");
        exit(1);
    }
    else
    {
       tmp = IsEmpty(S);
        printf("tmp is%d\n",tmp);
        while( !IsEmpty( S ) ){
            Pop( S );
        }
    }

}

void Pop( Stack S )
{
    PtrToStackNode FirstCell;
    printf("Pop Stack\n");

    if( IsEmpty( S ) )
    {
        printf("Pop Empty Stack\n");
        exit(0);
    }
    else
    {
        printf("free firstCell\n");
        FirstCell = S->Next;
        S->Next = S->Next->Next;
        free( FirstCell );
    }
}

void Push( ElementType E, Stack S )
{
    PtrToStackNode TmpCell;

    TmpCell = malloc( sizeof( struct StackNode ) );
    if( TmpCell == NULL )
        exit(0);
    else
    {
        TmpCell->Element = E;
        TmpCell->Next = S->Next;
        S->Next = TmpCell;
    }
}

void DisplayStack( Stack S )
{
    if( S == NULL )
        exit(0);
    else
    {
        while( S->Next != NULL){
            printf("echo something");
            printf("***%d***",S->Element);
            S = S->Next;
        }
    }
}

程序执行时输出

debug时初始化的Stack是空的,为什么程序跑起来的时候就不为空了呢?
为什么输出栈中元素这个字符串没有输出啊!
望指教!

解决方案

首先,Stack S定义的时候,系统是随机地给了S一个值,也就是所谓的悬挂指针(所以以后定义指针的时候一定要赋值为NULL!!)。所以它是不为空的,和debug是不一样的。

第二个问题。S->Next = S->Next->Next,如果你的S->Next指向了栈底元素,那么S->Next->Next是不是指向了一个非法的地址,可是这个地址是不为空的,判断了之后依然会再执行一次FirstCell = S->Next。最后,你free(FirstCell)的时候把不属于你的这一块地址也给free了,系统当然就给你非正常退出了程序了。也就是你后面的都不能执行了。

以上。

这篇关于C语言实现栈的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆