大家好,这里是国中之林!
❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看←
问题:
解答:
main.cpp
#include <iostream>
#include "Stack.h"
using namespace std;
const int MAX = 5;
int main()
{
Stack st(MAX);
Item item;
for (int i = 0; i < MAX; i++)
{
cout << "请输入一个无符号长整数:";
cin >> item;
while (cin.get() != '\n')continue;
if (st.push(item))
{
cout << item << "已经入栈!" << endl;
}
else
{
cout << "入栈失败!" << endl;
}
}
Stack st_new(st);
for (int i = 0; i < MAX; i++)
{
if (st_new.pop(item))
{
cout << item << "出栈成功!" << endl;
}
else
{
cout << "出栈失败!" << endl;
}
}
cout << "Bye" << endl;
return 0;
}
Stack.h
#pragma once
#include <iostream>
using namespace std;
typedef unsigned long Item;
class Stack
{
private:
enum{MAX=10};
Item* pitems;
int size;
int top;
public:
Stack(int n = MAX);
Stack(const Stack& st);
~Stack();
bool isempty()const;
bool isfull()const;
bool push(const Item& item);
bool pop(Item& item);
Stack& operator=(const Stack& st);
};
Stack.cpp
#include "Stack.h"
Stack::Stack(int n)
{
size = n;
pitems = new Item[size];
top = 0;
}
Stack::Stack(const Stack& st)
{
pitems = new Item[st.size];
for (int i = 0; i < st.size; i++)
{
pitems[i] = st.pitems[i];
}
size = st.size;
top = st.top;
}
Stack::~Stack()
{
if (pitems)
{
delete[] pitems;
}
}
bool Stack::isempty()const
{
if (top == 0)
{
return true;
}
else
{
return false;
}
}
bool Stack::isfull()const
{
if (top == size)
{
return true;
}
else
{
return false;
}
}
bool Stack::push(const Item& item)
{
if (isfull())
{
cout << "栈已满,无法入栈!" << endl;
return false;
}
pitems[top++] = item;
return true;
}
bool Stack::pop(Item& item)
{
if (isempty())
{
cout << "栈已空,无法出栈!" << endl;
return false;
}
item = pitems[--top];
return true;
}
Stack& Stack::operator=(const Stack& st)
{
if (this == &st)
{
return *this;
}
if (pitems)delete[] pitems;
pitems = new Item[st.size];
for (int i = 0; i < size; i++)
{
pitems[i] = st.pitems[i];
}
size = st.size;
top = st.top;
return *this;
}
运行结果:
考查点:
- 栈数据结构
- 动态内存分配
- 拷贝构造函数
- 赋值构造函数
- 析构
2024年9月8日10:58:48