关闭

栈的链表实现

526人阅读 评论(0) 收藏 举报
分类:

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


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:69756次
    • 积分:1464
    • 等级:
    • 排名:千里之外
    • 原创:73篇
    • 转载:22篇
    • 译文:0篇
    • 评论:12条
    最新评论