栈的链式实现

栈:先进后出
链式栈:一般不会遇到栈满的情况
主要掌握栈的入栈(Push)和出栈(Pop)操作

代码:

/*
    Name: Link_Stack
    Author: Bryant_xw
    Date: 2018-09-27-11.22.07
*/
#include<bits/stdc++.h>
using namespace std;

typedef struct Node
{
    int n;
    struct Node* next;
}StackNode;

typedef struct m_stack
{
    int nCount;
    StackNode* pTop;
}Stack;

void init(Stack** st)
{
    *st = (Stack*)malloc(sizeof(Stack));
    (*st)->nCount = 0;
    (*st)->pTop = NULL;
}

void Push(Stack* st, int num)
{
    if(st == NULL)
        return ;
    StackNode* temp = (StackNode*)malloc(sizeof(StackNode));
    temp->n = num;
    temp->next = st->pTop;
    st->pTop = temp;
    st->nCount++;
}

int Pop(Stack* st)
{
    if(st == NULL ||st->pTop == NULL)
        return -1;
    int res;
    StackNode *pDel = NULL;
    pDel = st->pTop;
    st->pTop = st->pTop->next;
    res = pDel->n;
    free(pDel);
    st->nCount--;
    return res;
}

bool IsEmpty(Stack* st)
{
    if(st->nCount == 0)
        return true;
    return false;
}

int GetStackTop(Stack* st)
{
    if(st == NULL)
        return -1;
    return st->pTop->n;
}

void Clear(Stack* st)
{
	if(st == NULL)
		return ;
	while(st->nCount != 0)
	{
		Pop(st);
	}
}

void Destory(Stack** st)
{
    Clear(*st);
    free(*st);
    *st = NULL;
}

int main(){
    Stack* st = NULL;
    init(&st);
    if(IsEmpty(st))
        printf("Stack is empty!\n");
    for(int i = 0; i < 5; ++i)
        Push(st,i+2);
    printf("Stack size is:%d\n",st->nCount);
    printf("top's num is %d\n",GetStackTop(st));
    printf("Stack contains: ");
    for(int i = 0; i < 5; ++i){
        if(i != 4)
            printf("%d ",Pop(st));
        else
            printf("%d",Pop(st));
    }
    puts("");

    return 0;
}



猜你喜欢

转载自blog.csdn.net/bryant_xw/article/details/84557642