棧結構

SanjiApollo發表於2017-07-13

棧的ADT

棧是有限制的線性結構,即元素要遵照後進先出(LIFO)的原則進出棧。
棧的主要操作有進棧(Push),出棧(Pop),判空(IsEmpty)等。
棧可由順序結構或者鏈式結構實現。

棧的鏈式結構實現

// stack.h宣告棧的結構和部分操作
#ifndef DS_LINK_STACK_H
#define DS_LINK_STACK_H
// a link stack

typedef char DataType;
struct StackNode;
typedef struct StackNode StackNode;
typedef struct StackNode *Stack;

// return an empty stack
Stack CreateStack(void);

// return 1 if the stack is empty, otherwise return 0
int IsEmptyStack(const Stack stack);

// push the data on the top
void Push(Stack stack, DataType data);

// return the top data
DataType Pop(Stack stack);

// make an empty stack
void MakeEmptyStack(Stack stack);

// destory the stack
void DestoryStack(Stack stack);

#endif
// 棧的一些操作的實現
#include<stdio.h>
#include<stdlib.h>
#include"stack.h"

struct StackNode{
    DataType data;
    StackNode *next;
};

int IsEmptyStack(const Stack stack) {
    return stack->next == NULL;
}

Stack CreateStack(void) {
    Stack S = (Stack) malloc (sizeof(StackNode));
    if(!S) {
        printf("memory is full, create stack failed!\n");
        return NULL;
    }
    S->next = NULL;
    return S;
}

void Push(Stack stack, DataType data) {
    if(stack == NULL) {
        printf("must create a stack first!\n");
        return ;
    }
    StackNode* node = (StackNode*) malloc (sizeof(StackNode));
    node->data = data;
    node->next = stack->next;
    stack->next = node;
}

DataType Pop(Stack stack) {
    if(stack == NULL) {
        printf("must create stack first!\n");
        exit(1);
    }
    if(IsEmptyStack(stack)) {
        printf("stack is empty! no data to pop!\n");
        exit(1);
    }
    StackNode *tmp = stack->next;
    DataType data = tmp->data;
    stack->next = tmp->next;
    free(tmp);
    return data;
}

void MakeEmptyStack(Stack stack) {
    if(stack == NULL) {
        printf("the stack doesn't exist! create one first!\n");
        return ;
    }
    if(IsEmptyStack(stack)) {
        printf("stack is already empty!\n");
        return ;
    }
    while(!IsEmptyStack(stack)) {
        Pop(stack);
    }
}

void DestoryStack(Stack stack) {
    if(stack == NULL) {
        printf("the stack doesn't exist!\n");
        return ;
    }

    free(stack);
}

相關文章