赞
踩
#ifndef STACK_H_
#define STACK_H_
#include <stdbool.h>
#define MAXSTACK 10
typedef char Item;
typedef struct stack
{
Item items[MAXSTACK]; // 使用字符数组
int top; // 栈顶的位置
} Stack;
// 初始化栈
void InitializeStack(Stack * ps);
// 确定栈是否已满
bool FullStack(const Stack * ps);
// 确定栈是否为空
bool EmptyStack(const Stack *ps);
// 把项压入栈
bool Push(Item item, Stack * ps);
// 把项弹出栈
bool Pop(Item * pitem, Stack * ps);
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stack.h"
void InitializeStack(Stack * ps)
{
ps->top=0;
}
bool FullStack(const Stack * ps)
{
return ps->top == MAXSTACK;
}
bool EmptyStack(const Stack *ps)
{
return ps->top == 0;
}
bool Push(Item item, Stack * ps)
{
if (!FullStack(ps))
{
ps->items[ps->top]=item;
ps->top++;
return true;
}
else
{
return false;
}
}
bool Pop(Item * pitem, Stack * ps)
{
if (!EmptyStack(ps))
{
*pitem = ps->items[ps->top-1];
ps->top--;
return true;
}
else
{
return false;
}
}
#include <stdio.h>
#include <string.h>
#include "stack.h"
char * s_gets(char * st, int n);
int main(void)
{
char input[MAXSTACK];
Stack ps;
char *ch;
InitializeStack(&ps);
puts("input your word:");
s_gets(input, MAXSTACK);
for(int i=0;i<MAXSTACK;i++)
Push(input[i],&ps);
while(ps.top>0)
{
Pop(ch,&ps);
printf("pop:%c\n",*ch);
}
return 0;
}
char * s_gets(char * st, int n)
{
char * ret_val;
char * find;
ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n'); // look for newline
if (find) // if the address is not NULL,
*find = '\0'; // place a null character there
else
while (getchar() != '\n')
continue; // dispose of rest of line
}
return ret_val;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。