栈的链式存储及常用操作

水水的实现一下链式栈。


#include <cstdio>
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

typedef struct Sta
{
    int data ;
    struct Sta *next ;
}Stack ;

void createStack(Stack *&s)   //建立一个带头结点的链栈
{
    s = (Stack*)malloc(sizeof(Stack)) ;
    s->next = NULL ;
    printf("新栈创建成功\n") ;
}


void destroyStack(Stack *&s)   //销毁一个链栈
{
    Stack *p = s ;
    Stack *q = s->next ;
    while(q != NULL)
    {
        free(p) ;
        p = q ;
        q = p->next ;
    }
    free(p) ;
}

int isEmpty(Stack *s)    //判定
{
    return (s->next == NULL) ;
}


void pushStack(Stack *&s,int e) //将元素e进栈
{
    Stack *p ;
    p = (Stack*)malloc(sizeof(Stack)) ;
    p->data = e ;
    p->next = s->next ;
    s->next = p ;
    printf("%d已经入栈成功\n",e) ;
}

void popStack(Stack *&s,int &e) //出栈操作,并且将出栈的元素保存到e中
{
    Stack *p = s->next ;
    e = p->data ;
    s->next = p->next ;
    free(p) ;
    printf("出栈成功\n") ;
}

void getTop(Stack *&s,int &e)
{
    if(s->next == NULL)
    {
        printf("栈为空,无法取得栈顶元素\n") ;
        return  ;
    }
    else
    {
        e = s->next->data ;
    }
}

int main()
{
    Stack *s ;
    createStack(s) ;
    pushStack(s,11) ;
    pushStack(s,12) ;
    if(isEmpty(s))
    {
        printf("栈为空\n") ;
    }else
    {
        printf("栈不为空\n") ;
    }
    int popNum ;
    popStack(s,popNum) ;
    printf("出栈的元素为%d\n",popNum) ;
    int top ;
    getTop(s,top) ;
    printf("栈顶元素是%d\n",top) ;
}




posted @ 2014-11-30 21:12  emoji  阅读(314)  评论(0编辑  收藏  举报