順序棧——9種基本操作和實現(C語言)
阿新 • • 發佈:2019-02-15
棧是僅限定在表尾進行插入和刪除操作的線性表,九種棧的基本操作;分別是構造 銷燬 清空 棧長 棧頂 插入 刪除 遍歷。下面就是程式碼實現:
//標頭檔案 #include<stdio.h> #include<string.h> #include<stdlib.h> #include<malloc.h> //巨集定義 #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 #define STACK_INIT_SIZE 100 #define STACKINCREMENT 10 typedef int ElemType; typedef int Status; //棧的順序結構表示 typedef struct { ElemType *base; ElemType *top; int stacksize; }SqStack; //1.構建一個空棧 Status InitStack(SqStack &S) { S.base = (ElemType*)malloc(STACK_INIT_SIZE*sizeof(ElemType)); if (!S.base) exit(OVERFLOW);//儲存分配失敗 S.top = S.base; S.stacksize = STACK_INIT_SIZE; return OK; } //2.銷燬棧 Status DestroyStack(SqStack &S) { S.top = NULL; S.stacksize = 0; free(S.base); return OK; } //3.清空棧 Status ClearStack(SqStack &S) { S.top = S.base; return OK; } //4.判斷棧是否為空 Status StackEmpty(SqStack S) { if (S.top == S.base) return ERROR; else return TRUE; } //5.求棧的長度 Status StackLength(SqStack S) { if (S.top == S.base) return FALSE; else return (S.top - S.base);//也可以直接返回S.top - S.base } //6.//求棧頂元素 Status GetTop(SqStack S, ElemType &e) { if (S.top == S.base) return FALSE; else e = *(S.top - 1); return e; } //7.棧頂插入元素 Status Push(SqStack &S, ElemType &e) { if (S.top - S.base >= STACK_INIT_SIZE) { S.base = (ElemType *)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(ElemType)); if (!S.base) { return false; } S.top = S.base + STACK_INIT_SIZE;//棧底地址可能改變,重新定位棧頂元素 S.stacksize = S.stacksize + STACKINCREMENT; } *S.top = e; S.top++; return OK; } //8.刪除棧頂元素 Status Pop(SqStack &S, ElemType &e) { if (S.top == S.base) return ERROR; else { S.top--; e = *S.top;//說明:此處容易使人迷惑,實際上此元素並沒真正刪除,仍在S.top中,但是如果插入元素,就會被更新,就像是刪除了一樣 return e; } } //9.遍歷棧 Status StackTraverse(SqStack S) { if (S.base == NULL) return ERROR; if (S.top == S.base) printf("棧中沒有元素……\n"); ElemType *p; p = S.top; while (p > S.base) { p--; printf("%d ",*p); } return OK; } //主函式檢驗九種操作 int main() { SqStack S; printf("構造一個空棧……\n"); InitStack(S); int i,n ; printf("輸入棧的長度:\n"); scanf("%d",&n); for (i = 1; i <= n; i++) { printf("輸入棧的第%d個元素\n",i); ++S.top; scanf("%d",S.top-1); } printf("……本棧是空棧嗎??……\n"); if (StackEmpty(S) == 1) printf("NO !!!\n"); else printf("YES !!!\n"); printf("……求出棧的長度……\n"); int m; m = StackLength(S); printf("棧的長度是:\n"); printf("%d\n",m); printf("遍歷輸出棧中的所有元素:\n"); StackTraverse(S); printf("\n"); printf("……輸出棧頂元素……\n"); int e; e = GetTop(S, e); printf("棧頂元素是:\n"); printf("%d\n",e); printf("……棧頂插入元素……\n"); printf("請輸入要插入的元素的數值:\n"); scanf("%d",&e); Push(S,e); printf("現在棧中的元素是:\n"); StackTraverse(S); printf("\n"); printf("……棧頂刪除元素……\n"); e = Pop(S,e); printf("被刪除的元素是:\n"); scanf("%d",&e); printf("現在棧中的元素是:\n"); StackTraverse(S); printf("\n"); printf("……清空棧……\n"); ClearStack(S); printf("現在棧中的元素是:\n"); StackTraverse(S); printf("……銷燬棧……\n"); if(DestroyStack(S)==1) printf("銷燬棧成功\n"); else printf("銷燬棧失敗\n"); printf("喜您成功完成所有的功能,畢竟您那麼帥!!!\n"); return 0; }