天天看点

栈Stack的链表实现

本节Jungle用链表指针实现栈和栈的基本操作(入栈、出栈、是否为空栈、打印栈元素、销毁栈)。

头文件List_Stack.h里定义栈结构和栈的基本操作:

#ifndef LIST_STACK
#define LIST_STACK

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

//栈顶指针
Stack* topNode;

bool isEmpty()
{
    return topNode == NULL;
}

void push(int iData)
{
    Stack *currentNode;
    currentNode = (Stack*)malloc(sizeof(Stack));
    if(currentNode == NULL)
        printf("分配内存失败!\n");
    currentNode->data = iData;
    currentNode->next = topNode;
    topNode = currentNode;
}

void pop()
{
    if(isEmpty())
    {
        printf("The Stack is Empty!\n");
        return;
    }
    Stack *currentNode;
    currentNode = topNode;
    topNode = topNode->next;

    free(currentNode);
}

///销毁栈
void deleteStack()
{
    Stack *tempNode;
    if(isEmpty())
    {
        printf("The Stack is Empty!\n");
        return;
    }
    tempNode = topNode;
    while(topNode->next!=NULL)
    {
        tempNode = topNode->next;
        free(topNode);
        topNode = tempNode;
    }
    free(topNode);
    topNode = NULL;
}

void printStack()
{
    if(isEmpty())
    {
        printf("The Stack is Empty!\n");
        return;
    }
    Stack *currentNode = topNode;
    while(currentNode != NULL)
    {
        printf("%d\t",currentNode->data);
        currentNode = currentNode->next;
    }
    printf("\n");
}

#endif //LIST_STACK
           

主程序里测试

#include <stdlib.h>
#include <stdio.h>
#include "List_Stack.h"

int main()
{
    int num=;

    int choice=;
    while(choice!=)
    {
        printf("请选择:\n\t1-是否为空栈\n\t2-入栈(push)\n\t3-出栈(Pop)\n\t4-打印\n\t5-销毁链表\n\t6-退出\n");
        scanf("%d",&choice);
        switch(choice)
        {
        case :
            if(isEmpty())
                printf("栈为空栈!\n");
            else
                printf("不是空栈!\n");
            break;
        case :
            int num;
            printf("请输入入栈元素值:");
            scanf("%d",&num);
            push(num);
            break;
        case :
            pop();
            break;
        case :
            printStack();
            break;
        case :
            deleteStack();
            break;
        }
    }

    system("pause");
    return ;
}
           
栈Stack的链表实现