C Primer Plus(第六版)17.12 编程练习 第5题

本文介绍了如何在C语言中使用结构体定义栈,包括栈的初始化、检查栈是否满或空、以及将输入的字符串项压入和弹出栈的操作。
摘要由CSDN通过智能技术生成

#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;
}

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值