关于顺序栈的简单操作如下, 由于主要介绍思想实现,读者从代码中可以很容易看出很多漏洞。如有错误之处,请大家指正!
点击(此处)折叠或打开
- #include<iostream>
- using namespace std;
- #define MAXSIZE 10
-
- struct Stack {
-
- int data[MAXSIZE];
- int top;
- };
-
- Stack *CreateStack(); //该步骤函数声明必须放在结构体后面
- void InitialStack(Stack *);
- void InsertStack(Stack *, int, int);
- void DeleteStack(Stack *, int);
- void PrintStack(Stack *);
-
- Stack *CreateStack() {
-
- Stack *p = new Stack; //创建指向栈的指针p
- p->top = -1; //因为是顺序栈,存储数据放在数组中,为了一致性,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 << "输出结束";
- cout << endl;
-
- }
-
- void InsertStack(Stack *p, int i, int x) {
-
- Stack *q;
-
- int length = p->top; //这里一定要注意,栈只能从一端进入弹出,要保证top指针不能够被修改
- p->top += 1; //由于插入一个数据,栈长度+1(更准确的说是数组下标+1)
- q = p;
-
- int llength = q->top;
- int flag = llength;
-
- for (int n = 0; n <= flag - i; n++) { //一定要保证变与不变,算法实现,通过图解读者可以清楚知道各参数意义
-
- 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++]; //删除操作,对于数组很简单就是覆盖操作
- }
-
- 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 << "出栈结束" << endl;
- }
-
- int main() {
-
- Stack *p;
-
- p = CreateStack();
- InitialStack(p);
-
- // InsertStack(p, 5, 11);
- //PrintStack(p);
-
- DeleteStack(p, 5);
- PrintStack(p);
- }
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29876893/viewspace-1814693/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/29876893/viewspace-1814693/