顺序栈的简单操作
關(guān)于順序棧的簡單操作如下, 由于主要介紹思想實(shí)現(xiàn),讀者從代碼中可以很容易看出很多漏洞。如有錯(cuò)誤之處,請大家指正!
#include<iostream>
using namespace std;
#define MAXSIZE 10
?struct Stack {
????int data[MAXSIZE];
????int top;
};
?Stack *CreateStack(); ? ? //該步驟函數(shù)聲明必須放在結(jié)構(gòu)體后面
?void?InitialStack(Stack *);
?void InsertStack(Stack *, int, int);
?void DeleteStack(Stack *, int);
?void PrintStack(Stack *);
Stack *CreateStack() {
????Stack *p = new Stack; ?//創(chuàng)建指向棧的指針p
????p->top = -1; ? ? ? ? ? //因?yàn)槭琼樞驐?#xff0c;存儲數(shù)據(jù)放在數(shù)組中,為了一致性,top指針置于-1,表明棧為空
????return p;
}
void InitialStack(Stack *p) {
????Stack *head;
????head = p;
????cout << "入棧的順序是:" << endl;
????
????int MAX_SIZE = MAXSIZE - 1;
????while (head->top != MAX_SIZE - 1) {
????????head->top++; ? //該步可以省略,下步改為:head->data[++head->top] = head->top;就是賦值與自加的先后順序
????????head->data[head->top] = head->top;
????????cout << head->data[head->top] << "-->";
????}
????cout << "輸出結(jié)束";
????cout << endl;
????
}
void InsertStack(Stack *p, int i, int x) {
????
????Stack *q;
????int length = p->top; //這里一定要注意,棧只能從一端進(jìn)入彈出,要保證top指針不能夠被修改
????p->top += 1; ? ? ? ? //由于插入一個(gè)數(shù)據(jù),棧長度+1(更準(zhǔn)確的說是數(shù)組下標(biāo)+1)
????q = p;
????int llength = q->top;
????int flag = llength;
????for (int n = 0; n <= flag - i; n++) {?//一定要保證變與不變,算法實(shí)現(xiàn),通過圖解讀者可以清楚知道各參數(shù)意義
????????q->data[llength--] = q->data[length--];?
????}
????q->data[i -1] = x;
????
}
void DeleteStack(Stack *p, int i) {
????Stack *q;
????int length = p->top;
????q = p;
????int l = i;
????int j = i - 1;
????for (int n = 0; n <= length - l+1; n++) {
????????q->data[j++] = q->data[i++]; ? //刪除操作,對于數(shù)組很簡單就是覆蓋操作
????}
????p->top = p->top - 1;
? ?
}
void PrintStack(Stack *p) {
????Stack *q;
????q = p;
????cout << "出棧的順序是:" << endl;
????while (q->top >=0) {
????????cout << q->data[q->top--] << "-->";
????????
????}
????cout << "出棧結(jié)束" << endl;
}
int main() {
????Stack *p;
????p = CreateStack();
???? InitialStack(p);
???// InsertStack(p, 5, 11);
????//PrintStack(p);
????DeleteStack(p, 5);
????PrintStack(p);
}
點(diǎn)擊(此處)折疊或打開
來自 “ ITPUB博客 ” ,鏈接:http://blog.itpub.net/29876893/viewspace-1814693/,如需轉(zhuǎn)載,請注明出處,否則將追究法律責(zé)任。
轉(zhuǎn)載于:http://blog.itpub.net/29876893/viewspace-1814693/
總結(jié)
- 上一篇: 安卓java百度地图api文档_Andr
- 下一篇: 克劳士比语录(转载)