注册 登录
编程论坛 数据结构与算法

顺序栈的操作问题

ltianc 发布于 2012-11-16 21:20, 497 次点击
#include<stdio.h>
#include<stdlib.h>

#define STACK_INIT_SIZE 100
#define INCREMENT 10
#define SElemType char

typedef struct
{
    SElemType *base;
    SElemType *top;
    int stacksize;
} SqStack;
int InitStack(SqStack *S)
{
    S->base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
    if(!S->base)
        return 0;
    S->base = S->top;
    S->stacksize = STACK_INIT_SIZE;

    return 1;
}

int StackEmpty(SqStack s)
{
    return (s.base == s.top );
}

int Push(SqStack *S, SElemType e)
{
    if(S->top - S->base >= S->stacksize)
    {
        S->base = (SElemType *)realloc(S->base, (INCREMENT + S->stacksize ) * sizeof(SElemType));
        S->top = S->base + S->stacksize;
        S->stacksize += INCREMENT;
    }
    *S->top = e;
    S->top ++;   
    return 1;
}

int StackLength(SqStack s)
{
    return (s.top - s.base);
}

int GetTop(SqStack s, SElemType *e)
{
    if(s.top == s.top)
        return 0;
    *e = *(s.top - 1);

    return 1;
}

int Pop(SqStack *S, SElemType *e)
{
    if(S->base == S->top )
        return 0;
    e = --S->top;

    return 1;
}
int ClearStack(SqStack *s)
{
    free(s);

    return 1;
}
int DispStack(SqStack s)
{
    int i;
    for(i =(int) s.top; i >= 0; i--)
        printf("%c", *(s.top - 1));

    return  1;
}

int main(void)
{
    SElemType e;
    SqStack S;
    printf("(1) 初始化栈 S\n");
    InitStack(&S);
    printf("(2)栈为 %s\n", (StackEmpty(S)? "空" : "非空"));
    printf("(3) 依次进栈元素 a, b, c, d, e\n");
    Push(&S, 'a');
    Push(&S, 'b');
    Push(&S, 'c');
    Push(&S, 'd');
    Push(&S, 'e');
    printf("(4)栈为 %s\n", (StackEmpty(S)? "空" : "非空"));
    printf("(5) 栈长度: %d\n",StackLength(S));
    printf("(6) 从栈顶到栈底元素f: ");
    DispStack(S);
    printf("(7)出栈序列: ");
    while(! StackEmpty(S))
    {
        Pop(&S, &e);
        printf("%c ", e);
    }
    printf("\n");
    printf("(8)栈为%s\n",(StackEmpty(S)? "空" : "非空"));
    printf("(9) 释放栈\n");
    ClearStack(&S);

    return 1;
}

这个程序编译,连接都没问题,就是运行出现了问题,还请各位高手给点指点,(是用C语言编的)
4 回复
#2
寒风中的细雨2012-11-18 11:15
程序代码:

int Push(SqStack *S, SElemType e)

 {
     if(S->top - S->base >= S->stacksize)
     {
         S->base = (SElemType *)realloc(S->base, (INCREMENT + S->stacksize ) * sizeof(SElemType));
         S->top = S->base + S->stacksize;
         S->stacksize += INCREMENT;
     }
     *S->top = e;
     S->top ++;  
    return 1;

 }

 

*S->top = e; 在这里死掉了
#3
寒风中的细雨2012-11-18 11:25
上面是属于非法内存访问  造成这个问题的原因在于这个函数中
程序代码:
int InitStack(SqStack *S)

 {
     S->base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
     if(!S->base)
         return 0;
     S->base = S->top;
     S->stacksize = STACK_INIT_SIZE;

    return 1;

 }
的 S->base = S->top;语句    应该是赋值的方向弄反了  导致后面操作了非法内存   正确的写法是:S->top = S->base;


#4
ltianc2012-11-18 20:19
回复 3楼 寒风中的细雨
嗯,非常感谢,我找了好长时间还没找到,
#5
ltianc2012-11-18 20:21
回复 2楼 寒风中的细雨
这个地方应该没问题,
1