链式栈的实现

LinkedStack.h

#pragma once
#include<stdio.h>
#include<stdlib.h>
struct node
{
    char data;
    struct node *next;
};
typedef struct node LStackNode;
typedef struct node* LinkStack;
//初始化链栈
void InitStack(LinkStack *top)
{
    if((*top = (LinkStack)malloc(sizeof(LStackNode))) == NULL)
        exit(-1);
    (*top)->next = NULL;

}
//判断链栈是否为空
int StackEmpty(LinkStack top)
{
    if(top->next == NULL)
        return 1;
    else
        return 0;
}
//进栈
int PushStack(LinkStack top,char e)
{
    LStackNode *p;
    if((p = (LStackNode*)malloc(sizeof(LStackNode))) == NULL)
    {
        printf("内存分配失败");
        exit(-1);
    }
    p->data = e;
    p->next = top->next;
    top->next = p;
    return 1;

}
//出栈
int  PopStack(LinkStack top, char* e)
{
    LStackNode* p;
    p = top->next;//栈顶
    if(!p)
    {
        printf("已经是空栈");
        return -1;

    }
    top->next = p->next;
    *e = p->data;
    free(p);
        return 1;

}
//取栈顶元素
int GetTop(LinkStack top,char *e)
{

    LStackNode *p;
    p = top->next;
    if(!p)
    {
        printf("已经是空栈");
        return -1;

    }
    *e = p->data;
    return 1;

}
//求链栈长度
int StackLength(LinkStack top)
{
    LStackNode *p;
    int count = 0;
    p = top;
    while(p->next != NULL)
    {
        p = p->next;
        count++;
    }
    return count;
}
//销毁链栈
void DestroyStack(LinkStack top)
{
    LStackNode *p,*q;
    p = top;
    while(!p)
    {
        q = p;
        p = p->next;
        free(q);

    }

}

LinkedStack.c

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"LinkedStack.h"
int main()
{
    LinkStack S;
    LStackNode* s;
    char ch[50],e,*p;
    InitStack(&S);
    printf("请输入进栈的字符:\n ");
    gets(ch);
    p = &ch[0];
    while(*p)
    {
        PushStack(S,*p);
        p++;
    }
    printf("当前的栈顶元素:");
    GetTop(S,&e);
    printf("%4c\n",e);
    printf("当前栈中的元素个数:%d\n",StackLength(S));
    printf("元素的出栈顺序是:");
    while(!StackEmpty(S))
    {
        PopStack(S,&e);
        printf("%4c",e);

    }
    printf("\n");
    return 0 ;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值