1、手动实现栈
#include <iostream>
#include <string.h>
using namespace std;
class stack
{
private:
int *a;
int top;
int size1;
public:
stack(int c):a(new int[c]),top(-1),size1(c){}
~stack(){delete[]a;}
int front()const
{
return a[top];
}
int back()const
{
return a[0];
}
bool empty()const
{
return top==-1;
}
int size()const
{
return top+1;
}
void push(int e)
{
if(top==size1-1)
{
return ;
}
a[++top]=e;
}
void pop()
{
if(top!=(-1))
{
--top;
}
else
{
cout<<"栈下溢"<<endl;
}
}
void Swap(int n,int m)
{
if(n<1||n>size()||m<1||m>size())
{
return ;
}
swap(a[n-1],a[m-1]);
}
void print() const
{
cout << "Stack: ";
for (int i = top; i >= 0; --i)
{
cout << a[i] << " ";
}
cout << endl;
}
};
int main()
{
stack s1(15);
s1.empty();
s1.push(5);
s1.push(2);
s1.push(9);
s1.push(1);
s1.print();
cout << "Size: " << s1.size() << std::endl;
cout << "Front: " << s1.front() << std::endl;
cout << "Back: " << s1.back() << std::endl;
s1.pop();
cout << "pop: ";
s1.print();
s1.Swap(1,3);
cout << "swap(1,3): ";
s1.print();
return 0;
}
2、手动实现队列
#include <iostream>
#include <string.h>
using namespace std;
class stack
{
private:
int *a;
int cap;
int size1;
int front1;
int rear;
public:
stack(int c):a(new int[c]),cap(c),size1(0),front1(0), rear(-1){}
~stack(){delete[]a;}
int front()
{
return a[front1];
}
int back()
{
return a[rear];
}
bool empty()
{
return rear==-1;
}
bool full()
{
return size1==cap;
}
int size()
{
return size1;
}
void push(int e)
{
if(cap==size1)
{
return ;
}
rear=(rear+1)%cap;
a[size1++]=e;
}
int pop()
{
if(rear!=(-1))
{
int e=a[front1];
front1=(front1+1)%cap;
size1--;
return e;
}
else
{
cout<<"队列为空"<<endl;
return 0;
}
}
//void Swap(int n,int m)
//{
// if(n<1||n>size()||m<1||m>size())
// {
// return ;
// }
// swap(a[n-1],a[m-1]);
//}
void print()
{
if(empty())
{
cout<<"队列为空"<<endl;
}
cout << "queue: ";
int count = 0;
int index = front1;
while (count < size1)
{
std::cout << a[index] << " ";
index = (index + 1) % cap;
count++;
}
cout << endl;
}
};
int main()
{
stack s1(5);
s1.empty();
s1.push(5);
s1.push(2);
s1.push(9);
s1.push(1);
s1.print();
cout << "Size: " << s1.size() << endl;
cout << "Front: " << s1.front() << endl;
cout << "Back: " << s1.back() << endl;
s1.pop();
cout << "pop: ";
s1.print();
//s1.Swap(1,3);
//cout << "swap(1,3): ";
//s1.print();
return 0;
}