数据结构——链栈(link stack)

/* linkStack.c */
/* 链栈 */

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

/* 链栈数据结构 */
/*
    ————————————————
    | value | next |   <--- top
    ————————————————
                ↓
    ————————————————
    | value | next |
    ————————————————
                ↓
    ————————————————
    | value | next |
    ————————————————
*/
typedef struct node {
    int data;
    struct node *next;
} StackNode;

void interface(void);
/* 链栈函数声明 */
StackNode *initializeLinkStack();
bool isEmptyLinkStack(StackNode*);
StackNode *pushLinkStack(StackNode*, int);
StackNode *popLinkStack(StackNode*);

/* 程序主函数入口 */
int main(){
    StackNode *top = initializeLinkStack();
    int flag, num;

    interface();
    for(;;){
        printf("Command: ");
        scanf("%d", &num);
        switch(num){
            case 0: puts("Bye!"); return 0; break;
            case 1:
                printf("Enter number: ");
                scanf("%d", &num);
                top = pushLinkStack(top, num);
                break;
            case 2:
                if(isEmptyLinkStack(top))
                    printf("Link stack is empty!\n");
                else
                    top = popLinkStack(top);
                break;
        }
    }

    return 0;
}

/* 用户界面 */
void interface(void){
    puts("+******************************+");
    puts("+  0, quit      退出           +");
    puts("+  1, push      压入           +");
    puts("+  2, pop       弹出           +");
    puts("+******************************+");
}
/* 链栈函数实现 */
/* 初始化链栈 */
StackNode *initializeLinkStack(){
    StackNode *top = (StackNode*)malloc(sizeof(StackNode));
    top = NULL;
    return top;
}
/* 链栈是否为空 */
bool isEmptyLinkStack(StackNode* top){
    if(top==NULL)
        return true;
    else
        return false;
}
/* 入栈 */
StackNode *pushLinkStack(StackNode *top, int number){
    StackNode *s = (StackNode*)malloc(sizeof(StackNode));
    s->data = number;
    s->next = top;
    top = s;
    return top;
}
/* 出栈 */
StackNode *popLinkStack(StackNode *top){
    int i = top->data;
    StackNode *p = top;
    top = top->next;
    free(p);
    printf("Pop: %d\n", i);
    return top;
}

 

转载于:https://www.cnblogs.com/noonjuan/p/11492024.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值