天天看點

棧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的連結清單實作