數據結構——鏈棧(link stack)


/* linkStack.c */
/* 鏈棧 */

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

/* 鏈棧數據結構 */
/*
    ————————————————
    | value | next |   <--- top
    ————————————————
                ↓
    ————————————————
    | value | next |
    ————————————————
                ↓
    ————————————————
    | value | next |
    ————————————————
*/
typedef struct node {
    int data;
    struct node *next;
} StackNode;

void interface(void);
/* 鏈棧函數聲明 */
StackNode *initializeLinkStack();
bool isEmptyLinkStack(StackNode*);
StackNode *pushLinkStack(StackNode*, int);
StackNode *popLinkStack(StackNode*);

/* 程序主函數入口 */
int main(){
    StackNode *top = initializeLinkStack();
    int flag, num;

    interface();
    for(;;){
        printf("Command: ");
        scanf("%d", &num);
        switch(num){
            case 0: puts("Bye!"); return 0; break;
            case 1:
                printf("Enter number: ");
                scanf("%d", &num);
                top = pushLinkStack(top, num);
                break;
            case 2:
                if(isEmptyLinkStack(top))
                    printf("Link stack is empty!\n");
                else
                    top = popLinkStack(top);
                break;
        }
    }

    return 0;
}

/* 用戶界面 */
void interface(void){
    puts("+******************************+");
    puts("+  0, quit      退出           +");
    puts("+  1, push      壓入           +");
    puts("+  2, pop       彈出           +");
    puts("+******************************+");
}
/* 鏈棧函數實現 */
/* 初始化鏈棧 */
StackNode *initializeLinkStack(){
    StackNode *top = (StackNode*)malloc(sizeof(StackNode));
    top = NULL;
    return top;
}
/* 鏈棧是否為空 */
bool isEmptyLinkStack(StackNode* top){
    if(top==NULL)
        return true;
    else
        return false;
}
/* 入棧 */
StackNode *pushLinkStack(StackNode *top, int number){
    StackNode *s = (StackNode*)malloc(sizeof(StackNode));
    s->data = number;
    s->next = top;
    top = s;
    return top;
}
/* 出棧 */
StackNode *popLinkStack(StackNode *top){
    int i = top->data;
    StackNode *p = top;
    top = top->next;
    free(p);
    printf("Pop: %d\n", i);
    return top;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM