#include <stdio.h> #include <stdlib.h> typedef int ElemType; typedef struct StackNode{ ElemType data; struct StackNode *next; }StackNode; StackNode *InitStack(StackNode *S);//初始化 StackNode * DestroyStack(StackNode*S);//銷燬 void ClearStack(StackNode*S);//清空 int StackEmpty(StackNode*S);//判空 int StackLength(StackNode*S);//棧長度 ElemType GetTop(StackNode*S);//獲取棧頂元素,不修改指針位置 StackNode *Push(StackNode*S, ElemType e);//插入棧頂 StackNode *Pop(StackNode *S, ElemType *e);//刪除棧頂 void StackTraverse(StackNode *S);//從棧頂依次遍歷 //初始化 StackNode *InitStack(StackNode *S){ S = NULL; printf("初始化成功\n"); return S; } //銷燬,返回空指針給S StackNode *DestroyStack(StackNode*S){ StackNode *p = S->next; while(p){ free(S); S = p; p = p->next; } printf("銷燬成功\n"); return NULL; } //清空 void ClearStack(StackNode*S){ printf("清空\n"); StackNode *p = S; while(p!=NULL){ p->data = 0; p = p->next; } printf("清空成功\n"); } //判空 int StackEmpty(StackNode*S); //棧長度 int StackLength(StackNode*S){ int len = 0; StackNode *p = S; while(p!=NULL){ len++; p = p->next; } return len; } //獲取棧頂元素,不修改指針位置 ElemType GetTop(StackNode*S){ if(S!=NULL){ printf("棧頂元素爲%d", S->data); return S->data; }else{ printf("空鏈棧無棧頂元素\n"); return NULL; } } //插入棧頂,返回指針指向當前棧頂 StackNode *Push(StackNode*S, ElemType e){ StackNode *p = NULL; p = (StackNode *)malloc(sizeof(StackNode)); p->data = e; p->next = S; S = p; printf("%d入棧成功\n", e); return S; } //刪除棧頂,返回指針指向當前棧頂 StackNode *Pop(StackNode *S, ElemType *e){ StackNode *p = NULL;//用於暫存刪除元素 if(S == NULL){ printf("空鏈棧,刪除失敗\n"); return NULL; } *e = S->data; p = S; S = S->next; free(p); printf("%d出棧成功\n",*e); return S; } //從棧頂依次遍歷 void StackTraverse(StackNode *S){ StackNode *p = S; if(p == NULL){ printf("空鏈棧\n"); return; } while(p != NULL){ printf("%d ", p->data); p = p->next; } printf("\n"); } int main(void){ StackNode *S; ElemType e; //初始化測試 S = InitStack(S); // //獲取棧頂元素測試 // GetTop(S); // S = Push(S, 999); // GetTop(S); //入棧測試 S = Push(S, 1); S = Push(S, 3); S = Push(S, 2); S = Push(S, 4); S = Push(S, 7); //棧長測試 printf("棧長%d\n",StackLength(S)); //遍歷測試 StackTraverse(S); // //出棧測試 // S = Pop(S, &e); // S = Pop(S, &e); // S = Pop(S, &e); // //printf("測試e是否改變: %d\n",e); // S = Pop(S, &e); // StackTraverse(S); // //清空測試 // ClearStack(S); // StackTraverse(S); //// //銷燬測試 // S = DestroyStack(S); // StackTraverse(S); return 0; }