C語言之實現(xiàn)棧的基礎創(chuàng)建
更新時間:2021年07月30日 08:21:43 作者:小尹同學
這篇文章主要介紹了C語言之實現(xiàn)棧的基礎創(chuàng)建,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下
棧:是限定僅在表尾進行插入和刪除操作的線性表!
棧的結構定義如下:
typedef struct Stack { SLDataType *base;//棧底元素的地址 int top;//棧頂元素的位置 } Stack;
棧的初始化如下:
SLDataType initStack(Stack &S) { S.base=(SLDataType*)malloc(N*sizeof(SLDataType));//申請棧元素的存儲空間 if(S.base==NULL) return -1; S.top=0; return 1; }
棧元素的輸入接口:
SLDataType pushStack(Stack &S,int e)//輸入棧的元素 { if(S.top==N) return 0; S.base[S.top]=e; S.top++; return 1; }
完整代碼如下:
#include<stdio.h> #include<stdlib.h> #define N 30 typedef int SLDataType; typedef struct Stack { SLDataType *base;//棧底元素的地址 int top;//棧頂元素的位置 } Stack; SLDataType initStack(Stack &S) { S.base=(SLDataType*)malloc(N*sizeof(SLDataType)); if(S.base==NULL) return -1; S.top=0; return 1; } SLDataType pushStack(Stack &S,int e)//輸入棧的元素 { if(S.top==N) return 0; S.base[S.top]=e; S.top++; return 1; } void printStack(Stack &S) { int i; i=0; while(i<S.top) { printf("%d ",S.base[i]); i++; } printf("\n"); } int main() { Stack S; int i,n,m;//n是入棧的個數(shù) if(initStack(S)==1) printf("棧初始化成功\n"); printf("入棧的元素個數(shù)為:"); scanf("%d",&n); i=1; printf("輸入要入棧的元素:"); while(i<=n) { scanf("%d",&m); if(pushStack(S,m)==0) { printf("%d入棧失??!\n",m); break; } i++; } printf("棧中的元素有: "); printStack(S);//打印棧中的元素 return 0; }
運行結果如下:
到此這篇關于C語言之實現(xiàn)棧的基礎創(chuàng)建的文章就介紹到這了,更多相關C語言之棧的創(chuàng)建內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C++如何將一個vector內容賦值給另一個vector,及swap與assign區(qū)別
在本文中,我們將主要介紹5種將一個vector內容賦值給另一個vector的方式,順便討論下swap與assign的區(qū)別,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08