作业:
1. 手动实现顺序栈,要求实现数据结构中,所有栈的相关操作
#include <iostream>
#define MAXSIZE 20 //宏定义,栈的最大容量
using namespace std;
template <typename T>
class stacklink
{
private:
T data[MAXSIZE]; //数据元素
int top = -1; //栈顶
public:
//无参构造
stacklink() {}
//有参构造
stacklink(T e):data(e){}
//析构函数
~stacklink(){}
//判空
bool empty()
{
return (top == -1); //栈空则返回1
}
//判满
bool full()
{
return (top == MAXSIZE-1); //栈满则返回1
}
//入栈
T push(T e)
{
if(1 == full())
{
cout << "栈满..." <<endl;
return -1;
}
top++;
data[top] = e;
return 0;
}
//出栈
T pop()
{
if(1 == empty())
{
cout << "栈空..." <<endl;
return -1;
}
cout << "出栈元素为: " << data[top] <<endl;
top--;
return 0;
}
//栈的遍历
void output();
};
//全局函数,栈的遍历
template <typename T>
void stacklink<T>::output()
{
cout << "栈内元素: ";
for(int i=0;i<=top;i++) //循环遍历栈
{
cout << data[i] <<" ";
}
cout <<endl;
}
int main()
{
stacklink<int> s;
s.push(2); //入栈
s.push(23);
s.push(44);
s.push(11);
s.output(); //遍历 2 23 44 11
s.pop(); //出栈 11
s.pop(); //出栈 44
s.output(); //遍历 2 23
return 0;
}
运行结果:
2. 手动实现循环顺序队列,要求实现数据结构中,所有队列的相关操作
#include <iostream>
#define MAXSIZE 20 //宏定义,队的最大容量
using namespace std;
template <typename T>
class queue
{
private:
T data[MAXSIZE]; //数据元素
int front = 0; //队头
int rear = 0; //队尾
public:
//无参构造
queue() {}
//有参构造
queue(T e):data(e){}
//析构函数
~queue(){}
//判空
bool empty()
{
return (front == rear); //队空则返回1
}
//判满
bool full()
{
return (front == (rear+1)%MAXSIZE); //队满则返回1
}
//入队
T push(T e)
{
if(1 == full())
{
cout << "队满..." <<endl;
return -1;
}
data[rear] = e;
rear = (rear+1)%MAXSIZE;
return 0;
}
//出队
T pop()
{
if(1 == empty())
{
cout << "队空..." <<endl;
return -1;
}
cout << "出队元素为: " << data[front] <<endl;
front = (front+1)%MAXSIZE;
return 0;
}
//队列的遍历
void output();
//队列元素个数计算
void count();
};
//全局函数,栈的遍历
template <typename T>
void queue<T>::output()
{
cout << "队内元素: ";
for(int i=front;i!=rear;i=(i+1)%MAXSIZE) //循环遍历队
{
cout << data[i] <<" ";
}
cout <<endl;
}
template <typename T>
void queue<T>::count()
{
cout << "队列中元素个数为: " << (MAXSIZE-front+rear)%MAXSIZE <<endl;
}
int main()
{
queue<int> q;
q.push(2); //入队
q.push(23);
q.push(44);
q.push(11);
q.output(); //遍历 2 23 44 11
q.count(); // 4
q.pop(); //出队 2
q.pop(); //出队 23
q.output(); //遍历 44 11
q.count(); //2
return 0;
}
运行结果: