线性表之栈
棧的定義:
一種只能在一端進行插入或刪除操作的線性表被稱為棧,其中允許刪除或插入的一端為棧頂,另一端為棧底,棧底固定不變;
棧的特點:先進后出,例如彈夾,先裝的子彈最后才能出;
按照存儲結構可以分為兩種棧:
- 順序棧
- 鏈式棧
棧的結構體定義:
順序棧:
//順序棧的結構體定義 typedef struct {int data[MaxSize];//棧頂指針int top; }SqStack;
鏈式棧:
//鏈棧結構體定義 typedef struct LNode {int data;struct LNode* next; }LNode;ps:有沒有發現鏈式棧和單鏈表定義一模一樣;其實棧的本質就是受約束的線性表;
基本算法:
判斷棧是否為空:
bool IsEmptyS(SqStack s) {if (s.top == -1)return true;elsereturn false; }棧是否為為滿:
bool IsFullS(SqStack s) {if (s.top == MaxSize - 1)return true;elsereturn false; }棧的初始化:
void InitialStack(SqStack &s) {//規定top=-1時為空棧s.top = -1; }入棧:
bool push(SqStack &s, int x) {if (s.top == MaxSize - 1)return false;s.data[++s.top] = x;return true; }出棧:
int pop(SqStack &s) {if (s.top == -1)return false;return s.data[s.top--];}打印整個棧:
void PrintStack(SqStack s) {if (s.top == -1) {cout << "棧空,無法打印" << endl;}int i = s.top;for (i; i >= 0; i--) {cout << s.data[s.top--]<<"\t";}cout << endl; }測試用例:
int main() {int a[4] = { 1,2,3,4 };SqStack s;InitialStack(s);cout << "順序棧測試" << endl;for (int i = 0; i < 4; i++) {push(s, a[i]);}PrintStack(s);cout << "2入棧" << endl;push(s, 2);cout << "10入棧" << endl;push(s, 10);PrintStack(s);cout << "出棧第一次\t" << pop(s) << endl;cout << "出棧第二次\t" << pop(s) << endl;cout << "出棧第三次\t" << pop(s) << endl;PrintStack(s);system("pause");return 0; }?
轉載于:https://www.cnblogs.com/zuixime0515/p/9613922.html
總結
- 上一篇: 小程序开发-利用canvas实现保存二维
- 下一篇: 小说中人称转换作用_长篇儿童小说《合欢》