堆栈--链式存储

/**
 * 栈--链式存储
 **/
#include <stdlib.h>
#include <iostream.h>

#define OK 1
#define ERROR 0

typedef struct node {   //链栈的结点结构
    int item;            //栈的数据元素类型
    struct node *next;  //指向后继结点的指针
}NODE; 

typedef struct stack{
    NODE *top;
}STACK; 

//初始化栈S  
void InitStack(STACK *S)
{
    S->top=NULL;
}

//入栈     
void Push(STACK *S,int item)
{
    NODE *p=(NODE*)malloc(sizeof(NODE));
    if (!p) exit(0);
    else 
    { 
        p->item=item;
        p->next=S->top;
        S->top=p;
    }
}

//判断栈S是否空  
int StackEmpty(STACK S)
{
    if (S.top==NULL) return 1;
    else 0;
}

//获取栈顶元素内容
 void GetTop(STACK S,int *item)
{
    if (StackEmpty(S)) exit(0);
    else *item=S.top->item;
}

//出栈
void Pop(STACK *S,int *item)
{
    if (StackEmpty(*S)) exit(0);
    else 
    { 
        *item=S->top->item;
        NODE *p=S->top;
        S->top=p->next; 
        free(p);
    }
}

 

posted @ 2013-02-23 17:56  何长春  阅读(149)  评论(0编辑  收藏  举报