#include <iostream> using namespace std;
#define MAXSIZE 20
typedef int ElemType; typedef struct { ElemType data[MAXSIZE]; int top1; //栈1栈顶指针 int top2; //栈2栈顶指针 } SqStack;
/* 构造一个空栈*/ bool InitStack(SqStack *Sq) { cout << "Init Stack ..." << endl; Sq->top1 = -1; //表示空栈 Sq->top2 = MAXSIZE;
return true; } /* 置为空栈 */ bool ClearStack(SqStack *Sq) { cout << "Clear Stack ..." << endl; Sq->top1 = -1; Sq->top2 = MAXSIZE; return true; }
bool StackEmpty(SqStack Sq) { if (Sq.top1 == -1 && Sq.top2 == MAXSIZE) return true; else return false; }
int StackLength(SqStack Sq) { cout << "Stack Length : "; return Sq.top1 + 1 + MAXSIZE - Sq.top2; } /* 返回栈顶元素 */ bool GetTop(SqStack Sq, ElemType *ptr, int StackNum) { if (StackNum == 1) { if (Sq.top1 != -1) { *ptr = Sq.data[Sq.top1]; cout << "Get Top1 Item " << *ptr << endl; return true; } return false; }
else if (StackNum == 2) { if (Sq.top2 != MAXSIZE) { *ptr = Sq.data[Sq.top2]; cout << "Get Top2 Item " << *ptr << endl; return true; } return false; } else { cout << "Stack Num must be 1 or 2!" << endl; return false; } }
/* 压栈 */ bool Push(SqStack *Sq, ElemType Elem, int StackNum) { if (StackNum == 1) { cout << "Push Item to Stack1 : " << Elem << endl; if (Sq->top1 + 1 == Sq->top2) //栈满 return false; Sq->data[++Sq->top1] = Elem; return true; } else if (StackNum == 2) { cout << "Push Item to Stack2 : " << Elem << endl; if (Sq->top1 + 1 == Sq->top2) return false; Sq->data[--Sq->top2] = Elem; return true; } else { cout << "Stack Num must be 1 or 2!" << endl; return false; } } /* 出栈 */ bool Pop(SqStack *Sq, ElemType *ptr, int StackNum) { if (StackNum == 1) { if (Sq->top1 == -1) return false;
*ptr = Sq->data[Sq->top1--]; cout << "Pop Item from Stack1 : " << *ptr << endl; return true; } else if (StackNum == 2) { if (Sq->top2 == MAXSIZE) return false; *ptr = Sq->data[Sq->top2++]; cout << "Pop Item from Stack2 : " << *ptr << endl; return true; } else { cout << "Stack Num must be 1 or 2!" << endl; return false; }
}
bool StackTraverse(SqStack Sq) { cout << "Traverse Stack ..." << endl; if (StackEmpty(Sq)) return false; cout << "Stack1 : "; for (int i = 0; i <= Sq.top1; i++) cout << Sq.data[i] << ‘ ‘; cout << endl; cout << "Stack2 : "; for (int i = MAXSIZE - 1; i >= Sq.top2; i--) cout << Sq.data[i] << ‘ ‘; cout << endl;
return true; }
int main(void) { SqStack Sq; InitStack(&Sq); for (int i = 0; i < 5; i++) Push(&Sq, i, 1); for (int i = 5; i < 10; i++) Push(&Sq, i, 2); StackTraverse(Sq); int result; Pop(&Sq, &result, 1); Pop(&Sq, &result, 2); StackTraverse(Sq); GetTop(Sq, &result, 1); GetTop(Sq, &result, 2); if (!StackEmpty(Sq)) cout << StackLength(Sq) << endl;
ClearStack(&Sq);
return 0; }
|