链栈的表示与实现

//不需要设表头结点,使用top指向栈顶元素
#include<iostream.h>
#include<stdlib.h>     //exit的原型定义
#define STACK_INIT_SIZE   100
#define OVERFLOW  -2
#define ERROR   0
#define OK  1
typedef int Status;
typedef char SElemType;

typedef struct SNode
{
    SElemType data;
    struct SNode *next;
}StackNode,*LinkStack;

void InitStack(LinkStack &top)
{
    top=NULL;
}

int StackEmpty(LinkStack top)
{
    return(top==NULL);
}

Status push(LinkStack &top,SElemType x)
{
    StackNode *p=new StackNode;
    if(!p)
        exit(OVERFLOW);
    p->data=x;
    p->next=top;
    top=p;
    return OK;
}

Status pop(LinkStack &top,SElemType &e)
{
    StackNode *p=top;
    if(StackEmpty(top))
        return ERROR;
    top=p->next;
    e=p->data;
    delete(p);
    return OK;
}

void create_stack(LinkStack &top)
{
    for(char ch='a';ch<='g';ch++)
        push(top,ch);
}

void StackTravers(LinkStack top)
{
    StackNode *p=top;
    while(p)
    {
        cout<<p->data<<"  ";
        p=p->next;
    }
    cout<<endl;
}

void MakeEmpty(LinkStack &top)
{
    StackNode *p;
    while(top!=NULL)
    {
        p=top;
        top=top->next;
        delete p;
    }
}

Status GetTop(LinkStack top,SElemType &e)
{
    if(StackEmpty(top))
        return ERROR;
    e=top->data;
    return OK;
}


void main()
{
    LinkStack top;
    SElemType e;
    InitStack(top);
    create_stack(top);
    StackTravers(top);

    cout<<"input Element e=";
    cin>>e;
    push(top,e);
    StackTravers(top);

    if(pop(top,e))
        cout<<"pop top element="<<e<<endl;
    else
        cout<<"Stack is Empty\n";

    if(GetTop(top,e))
        cout<<"get top element="<<e<<endl;
    else
        cout<<"Stack is Empty\n";

    MakeEmpty(top);

    if(pop(top,e))
        cout<<"pop top element="<<e<<endl;
    else
        cout<<"Stack is Empty\n";
}

 

posted on 2013-04-23 22:03  绕指柔yy  阅读(175)  评论(0编辑  收藏  举报

导航