突然想到很久沒有寫看看基本的資料結構了,所以決定回頭用C寫個stack,
順便複習一下指標的用法。
#include<stdio.h> #include<stdlib.h> typedef struct node{ char data1; struct node *Link; }NODE; NODE* initSteak(NODE *top){ top = NULL; return top; } NODE* pushSteak(NODE* top, char data){ NODE *newBlock; newBlock = (NODE*)malloc(sizeof(NODE)); newBlock->data1 = data; newBlock->Link = top; top = newBlock; return top; } NODE* popSteak(NODE *top){ NODE *tmpBlock = top; top = top->Link; free(tmpBlock); return top; } void listSteak(NODE *top){ while(!isEmpty(top)){ printf("%c ", top->data1); top = top->Link; } printf("\n"); } int isEmpty(NODE* top){ return (top == NULL); } int main(){ NODE *node; node = initSteak(node); node = pushSteak(node, 'a'); node = pushSteak(node, 'b'); listSteak(node); node = popSteak(node); listSteak(node); node = pushSteak(node, 'c'); node = pushSteak(node, 'd'); node = pushSteak(node, 'e'); listSteak(node); node = popSteak(node); node = popSteak(node); node = popSteak(node); listSteak(node); }
沒有留言:
張貼留言