栈的链表实现

stack1.h

#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED

typedef  int  ElementType;

struct  node;
typedef  struct node *PtrToNode;
typedef  PtrToNode  Stack;

int  IsEmpty(Stack  S);
Stack  CreatStack(void);
void   MakeEmpty(Stack S);
Stack   Push(ElementType  X, Stack S);
Stack   Pop( Stack  S);
ElementType Top(Stack S);

#endif // STACK_H_INCLUDED

stack1.c

#include  <stdio.h>
#include  <malloc.h>
#include  "stack1.h"

struct  node
{
    ElementType  data;
    PtrToNode  next;
};


int  IsEmpty(Stack  S)
{
    return  S->next ==NULL;
}
Stack  CreatStack(void)
{
    Stack S=(Stack)malloc(sizeof(struct node));
    if(S==NULL)
        printf("out  of  space!!!");

    S->next=NULL;
    MakeEmpty(S);
    return  S;
}

void   MakeEmpty(Stack S)
{
    if(S==NULL)
        printf("error!!!");
    else
        while(!IsEmpty(S))
           S=Pop(S);
}


Stack   Push(ElementType  X, Stack S)
{
    Stack temp;
    temp=(Stack)malloc(sizeof(struct node));
    temp->data=X;
    temp->next=S->next;
    S->next=temp;

    return  S;
}


Stack   Pop(Stack  S)
{
    Stack temp;
    temp=S->next;
    S->next=S->next->next;
    free(temp);

    return S;
}


ElementType Top(Stack S)
{
    if(!IsEmpty(S))
        return  S->next->data;
    else
            return  0;
}





main.c

#include <stdio.h>
#include <stdlib.h>
#include  "stack1.c"

int main()
{
    Stack  S;
    ElementType  c;
    S=(Stack)malloc(sizeof(struct node));

    S=CreatStack();
    while((c=getchar())!= EOF)
        S=Push(c,S);

    while(!IsEmpty(S))
    {
        if(Top(S)!='\n')
              printf("%d \t",Top(S));
         else
                printf("  ");
        S=Pop(S);
    }

    getchar();

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值