C语言的栈实现

链表结构实现

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <assert.h>
typedef struct _stack_node {
    struct _stack_node *next;
    int val;
} Stack_Node;

typedef struct _stack
{
    Stack_Node *top;
    size_t size;
} Stack;

Stack* createStack();
void freeStack(Stack* pStack);
void putStack(Stack* pStack, int value);
int popStack(Stack* pStack);
int peakStack(Stack* pStack);
bool emptyStack(Stack* pStack);
size_t sizeStack(Stack* pStack);

int main()
{
    Stack* pStack = createStack();
    int n = 0;
    while (scanf("%d", &n) , n!= -1)
    {
        putStack(pStack, n);
    }
    while (!emptyStack(pStack))
    {
        n = popStack(pStack);
        printf("%d ", n);
    }
    freeStack(pStack);
    return 0;
}

Stack* createStack()
{
    Stack* pStack = (Stack*)malloc(sizeof(Stack));
    pStack->top = NULL;
    pStack->size = 0;
    return pStack;
}
void freeStack(Stack* pStack)
{
    assert(pStack != NULL);
    Stack_Node* top = pStack->top;
    Stack_Node* p = NULL, *q = top;
    while(q)
    {
        p = q->next;
        free(q);
        q = p;
    }
}
void putStack(Stack* pStack, int value)
{
    assert(pStack != NULL);
    Stack_Node *node = (Stack_Node*)malloc(sizeof(Stack_Node));
    node->next = pStack->top;
    node->val = value;
    pStack->top = node;
    pStack->size++;
}
int popStack(Stack* pStack)
{
    assert(pStack != NULL);
    assert(false == emptyStack(pStack));
    Stack_Node *top = pStack->top;
    int val = top->val;
    pStack->top = top->next;
    pStack->size--;
    return val;
}
int peakStack(Stack* pStack)
{
    assert(pStack != NULL);
    assert(false == emptyStack(pStack));
    return pStack->top->val;
}
bool emptyStack(Stack* pStack)
{
    assert(pStack != NULL);
    return pStack->top == NULL;
}
size_t sizeStack(Stack* pStack)
{
    assert(pStack != NULL);
    return pStack->size;
}

本文已有113人次围观

添加新评论