基础知识
栈的基本操作
#include<iostream>
const int maxsize = 100;
using namespace std;
typedef int sElemType;
//顺序栈的储存结构
struct sqStack {
sElemType* base;
sElemType* top;
int stackSize;
};
//初始化
void initStack(sqStack& s)
{
s.base = new sElemType[maxsize];
s.top = s.base;
s.stackSize = maxsize;
}
//判断栈是否为空,若为空返回true,若非空返回false
bool isEmpty(sqStack& s)
{
if (s.top = s.base)
return true;
return false;
}
//入栈,插入元素e为新的栈顶元素
void push(sqStack& s, sElemType e)
{
if (s.top - s.base == s.stackSize)
cout << "Failed! The stack is full!\n";
*s.top = e;
s.top++;
}
//出栈,若栈不空则删除栈顶元素,用e返回其值
void pop(sqStack& s, sElemType& e)
{
if (s.top == s.base)
cout << "Failed! The stack is empty!\n";
e = *(--s.top);
}
//读取栈顶元素
sElemType getTop(sqStack s)
{
if (s.top == s.base)
cout << "Failed! The stack is empty!\n";
return *(s.top - 1);
}
//计算栈中元素个数
int count(sqStack s)
{
if (s.top == s.base)
cout << "Failed! The stack is empty!\n";
return s.top - s.base;
}
//打印栈
void printStack(sqStack s)
{
if (s.top == s.base)
cout << "Failed! The stack is empty!\n";
sElemType* p = s.base;
while (p != s.top)
{
cout <<" " << *p;
p++;
}
cout << endl;
}
int main()
{
sqStack s;
int e;
initStack(s);
cout << "Enter the element(Enter -1 to end): ";
cin >> e;
while (e != -1)
{
push(s, e);
cout << "Enter the element(Enter -1 to end): ";
cin >> e;
}
cout << "打印栈:";
printStack(s);
cout << "出栈,打印栈: ";
pop(s, e);
printStack(s);
e = getTop(s);
cout << "读取栈顶元素,栈顶元素=" << e << ",打印栈:";
printStack(s);
cout << "栈中元素个数=" << count(s) << endl;
return 0;
}
常见面试题
|