栈的链式存储及常用操作
生活随笔
收集整理的這篇文章主要介紹了
栈的链式存储及常用操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
水水的實現一下鏈式棧。
#include <cstdio> #include <iostream> #include <cstring> #include <cstdlib> using namespace std;typedef struct Sta {int data ;struct Sta *next ; }Stack ;void createStack(Stack *&s) //建立一個帶頭結點的鏈棧 {s = (Stack*)malloc(sizeof(Stack)) ;s->next = NULL ;printf("新棧創建成功\n") ; }void destroyStack(Stack *&s) //銷毀一個鏈棧 {Stack *p = s ;Stack *q = s->next ;while(q != NULL){free(p) ;p = q ;q = p->next ;}free(p) ; }int isEmpty(Stack *s) //判定 {return (s->next == NULL) ; }void pushStack(Stack *&s,int e) //將元素e進棧 {Stack *p ;p = (Stack*)malloc(sizeof(Stack)) ;p->data = e ;p->next = s->next ;s->next = p ;printf("%d已經入棧成功\n",e) ; }void popStack(Stack *&s,int &e) //出棧操作,并且將出棧的元素保存到e中 {Stack *p = s->next ;e = p->data ;s->next = p->next ;free(p) ;printf("出棧成功\n") ; }void getTop(Stack *&s,int &e) {if(s->next == NULL){printf("棧為空,無法取得棧頂元素\n") ;return ;}else{e = s->next->data ;} }int main() {Stack *s ;createStack(s) ;pushStack(s,11) ;pushStack(s,12) ;if(isEmpty(s)){printf("棧為空\n") ;}else{printf("棧不為空\n") ;}int popNum ;popStack(s,popNum) ;printf("出棧的元素為%d\n",popNum) ;int top ;getTop(s,top) ;printf("棧頂元素是%d\n",top) ; }
轉載于:https://www.cnblogs.com/emoji/p/4436863.html
總結
以上是生活随笔為你收集整理的栈的链式存储及常用操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计组之数据运算:2、奇偶校验码、海明校验
- 下一篇: LeetCode篇之链表:83(去重问题