数据结构--链栈

/*
* 链栈 
*/
#include <stdio.h>
#include <stack>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
#define OK 1
#define ERROR 0
typedef int ElemType; 
typedef int SElemType;
//链栈的存储结构
typedef struct StackNode{
    ElemType data;
    struct StackNode* next;
}StackNode,*LinkStack; 
//1.结构体初始化 
int InitStack(LinkStack &S){
    S = NULL;
    return OK;
} 
//2.入栈
int Push(LinkStack &S, ElemType e){
    StackNode* p;
    p = new StackNode;
    p->data = e;
    p->next = S->next;
    S = p;
    return OK;
} 
//3.出栈
int Pop(LinkStack &S){
    StackNode* p;
    if(S == NULL){
        return ERROR; 
    } 
    p = S;
    S = S->next;
    delete p;
    return OK;
} 
//4.取栈顶元素
int GetTop(LinkStack S){
    if(S != NULL){
        return S->data;
    }
} 
//5.打印,输出 
void Print(LinkStack S)
{//打印栈中元素,顺序是从栈底到栈顶
    StackNode *p;
    p = S;
    while (p == NULL)
    {
        printf("%d  ",(p->data));
        p = p->next;
    }
    printf("\n");
}

//主函数
int main(void){
    LinkStack S;
    int x,y;
    InitStack(S);
    printf("Enter Numbers:\n");
    while(true){
        scanf("%d",&x);
        if(x == 9999){
            break;
        }
        Push(S,x);              //构造顺序栈 
    } 
    printf("The stack elems:");
    Print(S);
    printf("1.入栈:");
    scanf("%d",&x);
    Push(S,x);
    printf("The stack elems:");
    Print(S); 
    y = GetTop(S);
    printf("2.取得栈顶元素:%d\n",y);
    printf("3.出栈:\n");
    Pop(S);
    printf("The stack elems:");
    Print(S);

}
posted @ 2017-06-30 09:27  滕鹏飞  阅读(152)  评论(0编辑  收藏  举报