数据结构-“栈”的基本操作
生活随笔
收集整理的這篇文章主要介紹了
数据结构-“栈”的基本操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
棧作為一種數據結構,是一種只能在一端進行插入和刪除操作的特殊線性表。它按照先進后出的原則存儲數據,先進入的數據被壓入棧底,最后的數據在棧頂,需要讀數據的時候從棧頂開始彈出數據(最后一個數據被第一個讀出來)
棧的更多概念就不贅述了,詳情可以參考百度百科。
接下來就來到了我們的動手環節,棧的基本操作包括入棧、出棧、初始化等.
棧頂指針:s.top,初始設置s.top=-1;棧頂元素:s.data[s.top]
進棧操作:棧不滿時,棧頂指針先加1,再送值到棧頂元素
出棧操作:棧非空時,先取棧頂元素值,再將棧頂指針減1
??諚l件:s.top==-1;棧滿條件:s.top==MaxSize-1;棧長:s.top+1
//棧 #include "stdafx.h"#define MaxSize 10 typedef int ElementType; typedef struct { ElementType data[MaxSize]; int top; }SqStack;/* 初始化棧 */ void InitStack(SqStack &s) { s.top=-1; }/* 判斷棧是否為空 */ bool StackEmpty(SqStack s) { if (s.top == -1) { return true; } return false; }/* 入棧 */ bool PushStack(SqStack &s, ElementType e) { //判斷棧是否已滿 if (s.top == MaxSize - 1) { return false; } s.top++; s.data[s.top] = e; return true; } /* 出棧 */ ElementType PopStack(SqStack &s) { //判斷是否為空 if (s.top == -1) { return NULL; } ElementType e = s.data[s.top]; s.top--; return e; }/* 獲取棧頂元素(注:并不是出棧,所以不需要top--) */ ElementType GetTop(SqStack s) { if (s.top == -1) { return NULL; } ElementType e = s.data[s.top]; return e; }void main() { SqStack stack; InitStack(stack); bool isEmpty = StackEmpty(stack); //printf_s("isEmpty=%s", isEmpty); PushStack(stack,1); PushStack(stack,2); PushStack(stack,3); PopStack(stack); ElementType e = GetTop(stack); //printf_s("getTop=%d", e); }總結
以上是生活随笔為你收集整理的数据结构-“栈”的基本操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 24位rgb真彩色到底是什么
- 下一篇: 中了打新债怎么卖出,有以下三个步骤