栈的链式存储实现

通过链式存储来实现对栈进行的各种操作。

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define OVERFLOW 1

typedef struct Node
{
    int data;
    struct Node *next;
}Node;

typedef struct LinkStack
{
    Node *top;//栈顶指针
    int count;//记录栈元素个数
}LinkStack;

//初始化
void InitLinkStack(LinkStack *S)
{
    S->top = (Node*)malloc(sizeof(Node));
    S->top->next = NULL;
    S->count = 0;
}

//栈顶元素
int GetTop(LinkStack *S)
{
    int n;
    n= S->top->data;
    printf("栈顶元素是%d\n",n);
    return 1;
}

//压栈
void Push(LinkStack *S,int n)
{
    Node *N;
    N = (Node*)malloc(sizeof(Node));
    N->data = n;
    N->next = S->top;
    S->top=N ;
    S->count ++;
}


//弹栈
void Pop(LinkStack *S)
{
    int n;
    Node *N;
    if(!(S->top))
        exit(OVERFLOW);
    N = S->top;
    n=N->data;
    printf("%d",n);
    S->count --;
    if( S->count == 0)
    {
        free(S->top);
        S->top = NULL;
    }
    else
    {
        N = S->top->next;
        free(S->top);
        S->top = N;
    }
}

//将十进制数转换为八进制
void conversion(int n)
{
    LinkStack *S;
    InitLinkStack(S);
    while(n)
    {
        Push(S,n%8);
        n=n/8;
    }
    while(S->count!=0)
    {
        Pop(S);
    }

}
int main()
{
    LinkStack *S;
    int i,k,n;
    S=(LinkStack*)malloc(sizeof(LinkStack));
    InitLinkStack(S);
    int quit=1;
    while(quit==1)
    {
        printf("1.Push 2.Pop 3.getTop 4.conversion\n");
        scanf("%d",&k);
        getchar();
        switch(k)
        {
            case 1:
                printf("Push number \n");
                scanf("%d",&i);
                Push(S,i);
                break;
            case 2:
                printf("Pop number is ");
                Pop(S);
                printf("\n");
                break;
            case 3:
                GetTop(S);
                break;
            case 4:
                printf("Conversion number is ");
                scanf("%d",&n);
                conversion(n);
                break;
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值