数据结构——堆栈的C语言实现
生活随笔
收集整理的這篇文章主要介紹了
数据结构——堆栈的C语言实现
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1.什么叫堆棧?
2.堆棧的數(shù)據(jù)類型描述
3.堆棧順序存儲的C語言實現(xiàn)
#include<stdio.h> #include<stdlib.h>#define MaxSize 10 #define ERROR -1 #define ElementType int typedef struct SNode *Stack; struct SNode{ElementType Data[MaxSize];int Top; };Stack PtrS; //1.初始化 Stack MakeEmpty() {Stack PtrS;PtrS = (Stack)malloc(sizeof(struct SNode));PtrS->Top=-1;return PtrS; }//2.入棧 void Push(ElementType item,Stack PtrS) {if(PtrS->Top==MaxSize){printf("棧已滿\n");return;}else{PtrS->Data[++(PtrS->Top)]=item;return;} }//3.出棧 ElementType Pop(Stack PtrS) {if(PtrS->Top==-1){printf("棧為空\n");return ERROR;}else{return PtrS->Data[(PtrS->Top)--];} }int main() {int i;PtrS=MakeEmpty();Push(23,PtrS);Push(28,PtrS);Push(78,PtrS);for(i=0;i<=PtrS->Top;i++ ){printf("%d ",PtrS->Data[i]);}printf("\n");printf("出棧為:%d\n",Pop(PtrS));for(i=0;i<=PtrS->Top;i++ ){printf("%d ",PtrS->Data[i]);} printf("\n");return 0; }4.堆棧鏈式存儲的C語言實現(xiàn)
#include<stdio.h> #include<stdlib.h>#define ElementType int typedef struct SNode *Stack; struct SNode{ElementType Data;Stack Next; }; Stack PtrS;//1.初始化 Stack MakeEmpty() {Stack PtrS;PtrS = (Stack)malloc(sizeof(struct SNode));PtrS->Next=NULL;return PtrS; }//2.判斷堆棧是否為空,空為1,不空為0 int IsEmpty(Stack PtrS) {return (PtrS->Next==NULL); }//3.入棧 void Push(ElementType item,Stack PtrS) {Stack TmpCell;TmpCell = (Stack)malloc(sizeof(struct SNode));TmpCell->Data=item;TmpCell->Next=PtrS->Next;PtrS->Next=TmpCell; }//4.出棧 ElementType Pop(Stack PtrS) {ElementType TopElement;Stack FirstCell;if(IsEmpty(PtrS)){printf("棧為空\n");return 0;}else{FirstCell=PtrS->Next;PtrS->Next=FirstCell->Next;TopElement=FirstCell->Data;free(FirstCell);return TopElement;} }int main() {int i;PtrS=MakeEmpty();Push(41,PtrS);printf("%d\n",PtrS->Next->Data);Push(14,PtrS);Push(67,PtrS);Stack S=PtrS;for(i=0;i<3;i++){S=S->Next;printf("%d ",S->Data);}printf("\n");Stack S2=PtrS;printf("出棧為:%d\n",Pop(S2));for(i=0;i<2;i++){S2=S2->Next;printf("%d ",S2->Data);}printf("\n");return 0; }總結
以上是生活随笔為你收集整理的数据结构——堆栈的C语言实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Jupyter notebook绘制热力
- 下一篇: 计算机网络(十三)-数据链路层-动态分配