queue
#include <iostream>
using namespace std;
class Node {
public:
double data;
Node* next;
};
class Queue
{
public:
Queue();
~Queue();
bool Empty(void);
void Enqueue(double x);
bool Dequeue(double &x);
void DisplayQueue(void);
private:
Node* front;
Node* rear;
int count;
};
Queue::Queue()
{
front = rear = NULL;
count = 0;
}
Queue::~Queue()
{
double value;
while (Empty())
Dequeue(value);
}
bool Queue::Empty()
{
if (count)
return false;
else
return true;
}
void Queue::Enqueue(double x)
{
Node* newNode = new Node;
newNode->data = x;
newNode->next = NULL;
if (Empty())
{
front = newNode;
rear = newNode;
}
else
{
rear->next = newNode;
rear = newNode;
}
count++;
}
bool Queue::Dequeue(double &x)
{
if (Empty())
{
cout<< " the queue is empty" << endl;
return false;
}
else
{
x= front->data;
Node* nextNode = front->next;
delete front;
front = nextNode;
count--;
}
}
void Queue::DisplayQueue()
{
cout<< "front -->";
Node* Node2 = front;
for (int i = 0; i < count; i++)
{
cout << Node2->data;
if (i != count - 1)
cout << endl;
else
cout << "\t<--rear" << endl;
Node2=Node2->next;
}
}
int main(void)
{
Queue queue;
for (int x = 0; x < 5; x++)
queue.Enqueue(x);
cout<< "输出" << endl;
queue.Enqueue(5);
queue.DisplayQueue();
double value;
queue.Dequeue(value);
cout<< "删除 = " << value << endl;
queue.DisplayQueue();
queue.Enqueue(7);
queue.DisplayQueue();
return 0;
}
stack
#include <iostream>
using namespace std;
template<typename T>
class stack
{
private:
T * botton;
T * last;
T * top;
public:
stack(int size = 2) {
botton = new T[size];
last = botton;
top = botton + size;
}
~stack()
{
delete []botton;
botton = last = top = nullptr;
}
stack(const stack &other)
{
int len = other.last-other.botton;
int size = other.top - other.botton;
this->botton = new T[size];
memcpy(this->botton, other.botton, len*sizeof(T));
this->last = this->botton+len;
this->top = this->botton+size;
}
bool empty()
{
return this->botton == this->last;
}
bool full()
{
return this->last == this->top;
}
void greater()
{
int size = this->top - this->botton;
T *temp = new T[size+1];
memcpy(temp, this->botton, size*sizeof (T));
delete []botton;
botton = temp;
last = botton+size;
top= botton+ size+1;
}
void push_back( const T val)
{
if(this->full())
{
this->greater();
}
*last = val;
last++;
}
void pop_back()
{
if(this->empty())
{
return;
}
--last;
}
T front() const
{
return *botton;
}
int size()
{
return top-botton;
}
int len()
{
return last-botton;
}
T &at(int index)
{
if(index<0 || index>this->len())
{
cout<<"访问越界"<<endl;
}
return botton[index];
}
};
int main()
{
stack<int> s;
for(int i=1; i<=20; i++)
{
s.push_back(i);
cout<<s.size()<<endl;
}
return 0;
}