1. 程式人生 > 實用技巧 >棧的鏈式結構

棧的鏈式結構

 1 //鏈式棧
 2 #include<stdio.h>
 3 #include<stdlib.h>
 4 typedef struct Node {
 5     char a;
 6     struct Node* next;
 7 }NODE;
 8 //節點
 9 typedef struct StackLink {
10     int count;    //棧裡面的數的個數
11     NODE* head;    //棧的頭的位置
12 }StackLink;
13 typedef int        Status;
14 
15 StackLink* test = (StackLink*)malloc
(sizeof(StackLink)); 16 void initStackLink() 17 { 18 test->count = 0; 19 test->head = NULL; 20 } 21 Status Push(char p) 22 { 23 NODE* temp = (NODE*)malloc(sizeof(NODE)); 24 if (temp == NULL) 25 { 26 return 0; 27 } 28 temp->a = p; 29 temp->next = test->head;//
申請到的記憶體的地址指向之前的棧的首地址 30 test->head = temp; //將頭指標指向新申請的地址 31 test->count++; //棧的空間加大 32 return 1; 33 } 34 Status Pop() 35 { 36 if (test->head == NULL) 37 { 38 return 0;//空棧 39 } 40 else 41 { 42 NODE* temp = test->head;; 43 printf("
%c已出棧", test->head->a); 44 test->head = test->head->next;//將頭指標下移 45 free(temp); 46 temp = NULL;//釋放原頭指標的記憶體 47 test->count--;//棧的大小減小 48 return 1; 49 } 50 } 51 int main() 52 { 53 initStackLink(); 54 Push('a'); 55 Push('b'); 56 Pop(); 57 Pop(); 58 }