首页 > 代码库 > 链栈实现

链栈实现

#include<iostream>
#include<cstdio>
#include<cstdlib>

using namespace std;
#define TRUE 1
#define FALSE 0
typedef int ElemType;

typedef struct node
{
    ElemType data;
    struct node *next;
}StackNode, *LinkStack;

void InitStack(LinkStack top)
{
    top->next=NULL;
}

int IsEmpty(LinkStack top)
{
    if(top->next==NULL)
        return TRUE;
    return FALSE;
}

int Push(LinkStack top, ElemType e)
{
    StackNode *temp;
    temp=(LinkStack)malloc(sizeof(StackNode));
    if(temp==NULL) return FALSE;
    temp->data=http://www.mamicode.com/e;
    temp->next=top->next;
    top->next=temp;
    return TRUE;
}

int Pop(LinkStack top, ElemType *e)
{
    if(IsEmpty(top)) return FALSE;
    StackNode *temp=top->next;
    *e=temp->data;
    top->next=temp->next;
    free(temp);

    return TRUE;
}

void GetTop(LinkStack top, ElemType *e)
{
    *e=top->next->data;
}

int main()
{
    LinkStack s;
    s=(LinkStack)malloc(sizeof(StackNode));
    InitStack(s);
    for(int i=0; i<10; i++)
        Push(s, i);
    int ans;
    while(!IsEmpty(s))
    {
        Pop(s, &ans);
        printf("%d ", ans);
    }
    printf("\n");
    return 0;
}

 

链栈实现