1. 程式人生 > 其它 >棧程式碼演示

棧程式碼演示

棧程式碼演示

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

//節點結構體
typedef struct Node
{
    int data;
    struct Node * pNext;
}Node, *pNode;

//棧結構體
typedef struct Stack
{
    pNode ptop;
    pNode pbottom;
}Stack, *pStack;

void init_stack(pStack pstack);
void push_stack(pStack pstack, int
val); void show_stack(pStack pstack); void pop_stack(pStack pstack, int *val); void clear_stack(pStack pstack); void main(void) { Stack stack; int val; init_stack(&stack); push_stack(&stack, 4); push_stack(&stack, 5); push_stack(&stack, 6); show_stack(&stack); pop_stack(
&stack, &val); printf("出棧元素的值為: %d\n", val); show_stack(&stack); clear_stack(&stack); show_stack(&stack); return; } /* 函式名:init_stack 作用:初始化一個棧 輸入:pStack pstack 輸出:無 */ void init_stack(pStack pstack) { pNode p; p = (pNode)malloc(sizeof(Node)); p->pNext = NULL;
if (p == NULL) { return; } pstack->pbottom = p; pstack->ptop = p; return; } /* 函式名:push_stack 作用:向棧內壓入一個元素 輸入:pStack pstack, int val(壓入棧中的值) 輸出:無 */ void push_stack(pStack pstack, int val) { pNode p; p = (pNode)malloc(sizeof(Node)); p->data = val; if (p == NULL) { return; } p->pNext = pstack->ptop; //注意p->pNext 指向 棧頂 pstack->ptop = p; return; } /* 函式名:show_stack 作用:顯示棧中的元素 輸入:pStack pstack 輸出:無 */ void show_stack(pStack pstack) { pNode p; p = (pNode)malloc(sizeof(Node)); if (p == NULL) { return; } p = pstack->ptop; printf("stack中的元素為:"); if (pstack->pbottom == pstack->ptop) { printf(""); } while (p != pstack->pbottom) { printf("%d、", p->data); p = p->pNext; } printf("\n"); return; } /* 函式名:pop_stack 作用:出棧一個元素 輸入:pStack pstack, int *val(出棧元素的值) 輸出:無 */ void pop_stack(pStack pstack, int *val) { pNode p; p = (pNode)malloc(sizeof(Node)); if (p == NULL) { return; } p = pstack->ptop; *val = p->data; pstack->ptop = p->pNext; free(p); return; } /* 函式名:clear_stack 作用:清空棧 輸入:pStack pstack 輸出:無 */ void clear_stack(pStack pstack) { pNode p; p = (pNode)malloc(sizeof(Node)); if (p == NULL) { return; } while (p != pstack->pbottom) { p = pstack->ptop; pstack->ptop = p->pNext; free(p); p = pstack->ptop; } return; }
我們嚮往遠方,卻忽略了此刻的美麗