栈的代码, 比较容易实现:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;
class Point{
public:
int x, y;
Point(int x, int y):x(x), y(y){}
Point(){}
};
template<class T>
class Stack{
public:
Stack(){
cur = 0;
}
private:
T s[1000];
int cur;
public:
void push(T t){
s[cur++] = t;
}
T top(){
return s[cur - 1];
}
void pop(){
cur--;
}
};
int main()
{
Stack<Point>s;
s.push(Point(1, 2));
s.push(Point(4, 5));
//s.pop();
cout << s.top().x << endl;
return 0;
}
队列的代码, 有链表实现:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;
class Node{
public:
Node *next;
Node *pre;
int t;
Node(){
next = NULL; //这两个都得是NULL
pre = NULL;
}
Node(int t):t(t){
}
};
template<class T>
class Link{
public:
T *head; //指向队列头
T *tell; //指向队列尾
int len;
Link(){
head = new T(); //一开始为脑袋实例化, 注意head里面不存数据, 只是标识队列
tell = NULL; //一开始尾巴为空
len = 0;
}
void insert(T t){
T *newT = new T();
*newT = t; //为声明的空间赋值, 这里需要重载T的赋值符号=
//让老二和newT关联
T *tmp = head->next;
newT->next = tmp;
if(NULL != tmp) //如果没有老二
tmp->pre = newT;
//让新的老二和脑袋关联
head->next = newT;
newT->pre = head;
//当长度为0的时候就更新tell的指向
if(0 == len){
tell = newT;
}
len++;
}
T front(){
if(0 == len)
return NULL;
return *tell;
}
void pop(){
if(0 == len){
tell = NULL;
return;
}
else{ //删除尾指针所指向的空间后更新尾指针的指向
T *tmp = tell->pre;
delete tell;
tell = tmp;
len--;
}
}
bool empty(){
return 0 == len;
}
};
int main(){
Link<Node>l;
l.insert(Node(12));
l.insert(Node(23));
l.insert(Node(27));
l.pop();
l.pop();
l.pop();
if(!l.empty())
cout << l.front().t << endl;
else{
cout << "l is empty" << endl;
}
return 0;
}