cXiaoLee
cXiaoLee
2019-04-27 12:09

新手c语言的压栈与弹栈 写了一段代码压入字符串与弹出字符串 始终读不出来 不知道哪里出错了

  • c++
  • c语言

//这是主函数
#include "stdio.h"
#include "stdlib.h"
#include "stack_array.h"

int main()
{
char *arr[] = {"a","b","c","d","e","f"};
STACK *stack = stack_create(20);

//压栈
while(!stack_full(stack))
{
    stack_pull(stack,*arr);
}

//弹栈
while(stack_emputy(stack))
{
    printf("%s\n",stack_pop(stack));
}
stack_destroy(stack);
return 0;

//这是栈函数
#include "stdio.h"
#include "stdlib.h"
#include "stack_array.h"

STACK *stack_create(int cap)
{

STACK *stack = (STACK*)malloc(sizeof(STACK));
stack->array = (char*)malloc(cap*sizeof(char));
stack->cap = cap;
stack->top = 0;
return stack;

}

void stack_destroy(STACK *stack)
{

free(stack->array);
free(stack);

}

//先判断栈满
int stack_full(STACK *stack)
{

if((stack->top)>=stack->cap)
{
    return 1;
}
else
{
    return 0;
}

}

//判断栈空
int stack_emputy(STACK *stack)
{

if(stack->top == 0)
{
    return 1;
}
else
{
    return 0;
}

}

//进行压栈
void stack_pull(STACK *stack,char *arr)
{

int num = 0;
stack->array[stack->top++] =arr[num];
num++;

}
//弹栈
int stack_pop(STACK *stack)
{

return stack->array[--stack->top];

}

//头文件
#ifndef STACK_ARRAY
#define STACK_ARRAY

typedef struct
{

char *array;
int cap;
int top;

}STACK;

//创建栈

STACK *stack_create(int cap);

//销毁栈

void stack_destroy(STACK *stack);

//压栈

void stack_pull(STACK *stack,char *arr);

//弹栈

int stack_pop(STACK *stack);

//判断栈是否已满

int stack_full(STACK *stack);

//判断栈是否为空

int stack_emputy(STACK *stack);

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答