目录
堆栈与队列算法-以数组来实现堆栈
C++代码
扑克牌发牌算法
C++代码
堆栈与队列算法-以数组来实现堆栈
以数组结构来实现堆栈的好处是设计的算法都相当简单。不过,如果堆栈本身的大小是变动的,而数组大小只能事先规划和声明好,那么数组规划太大了浪费空间,规划太小了则不够用,这是以数组来实现堆栈的缺点。
C++代码
用循环来控制元素压入堆栈或弹出堆栈,并仿真堆栈的各种操作,其中必须包括压入(push)与弹出(pop)函数,并在最后输出堆栈内的所有元素。
#include<iostream>
using namespace std;
class Stack {
private:
int MaxStack;
int* data;
int top;
public:
Stack(int tempMaxStack) {
this->MaxStack = tempMaxStack;
data = new int[MaxStack];
top = -1;
}
bool IsEmpty() {
if (top == -1)
return true;
else
return false;
}
void Push(int tempData) {
if (top < MaxStack) {
++top;
data[top] = tempData;
}
}
void Pop() {
if (top != -1) {
top--;
}
}
int GetTop() {
if (top != -1) {
return data[top];
}
}
};
int main() {
Stack* stack = new Stack(10);
int value;
cout << "请输入10个数据:" << endl;
for (int i = 0; i < 10; i++) {
cin >> value;
stack->Push(value);
}
cout << "================" << endl;
while (!stack->IsEmpty()) {
cout << "从堆栈中弹出数据:" << stack->GetTop() << endl;
stack->Pop();
}
cout << "================" << endl;
delete stack;
return 0;
}
输出结果
扑克牌发牌算法
C++代码
以数组仿真扑克牌洗牌和发牌的过程。以随机数生成扑克牌后放入堆栈,放满52张牌后开始发牌,使用堆栈功能来给4个人发牌。
#include<iostream>
#include<iomanip>
using namespace std;
class Card {
private:
int card[52];
int stack[52];
string suit[4] = { "草花", "方块", "红桃", "黑桃" };
int top;
public:
Card() {
for (int i = 0; i < 52; i++) {
card[i] = i + 1;
stack[i] = card[i];
}
top = -1;
}
bool IsEmpty() {
if (top == -1)
return true;
else
return false;
}
void Push(int tempData) {
if (top < 52) {
top++;
stack[top] = tempData;
}
}
void Pop() {
if (top != -1) {
top--;
}
}
int GetTop() {
if (top != -1) {
return stack[top];
}
}
void SwapCard() {
srand((unsigned)time(NULL));
for (int i = 0; i < 52; i++) {
int j = rand() % 51 + 1;
int temp = card[i];
card[j] = card[i];
card[i] = temp;
}
int i = 0;
while (i != 52) {
Push(card[i]);
i++;
}
}
void DealCard() {
while (!IsEmpty()) {
cout << "[" << suit[(GetTop() - 1) / 13] << setw(3) << GetTop() % 13 + 1 << "]\t";
if (top % 4 == 0)
cout << endl;
Pop();
}
}
};
int main() {
Card* card = new Card;
cout << "洗牌中,请稍等:" << endl;
card->SwapCard();
cout << "发牌:" << endl;
cout << "东家\t\t北家\t\t西家\t\t南家" << endl;
cout << "======================================================" << endl;
card->DealCard();
return 0;
}
输出结果