题目:
用一个数组表示队列,只有front指针,没有rear指针,用count计数,实现pop操作。
template <class T>
class Queue {
private:
int count;
T *front;
public:
Queue(int m = 0);
~Queue();
bool pop();
};
Queue<T>::Queue(int m = 0) {
count = 0;
m && front = new T[m];
}
Queue<T>::~Queue() {
delete [] front;
}
bool Queue<T>::pop() {
if(count == 0) {
std::cout << "Queue is full" << endl;
return false;
}
for(int i = 0; i < count-1; ++i) {
front[i] = front[i+1];
}
--count;
return true;
}
题目:
假设以带头结点的循环链表表示队列,并且只设一个指针指向队尾元素(不设头结点),编写相应的入队函数。
void push(const T & item) {
Link<T>* tmp = new Link<T>(item);
tmp->next = tail->next;
tail->next = tmp;
tail = tail->next;
}
题目:
在一个长度为n的数组中实现两个栈,(总元素不超过n),保证push和pop为O(1)时间
分析:有两种方式:
1.将数组的两端看成栈底,同时向中间延伸
2.将数组的中间看成栈底,向数组两边延伸
这两种比较的话,明显第一种方式更加优秀。因为第二种限制了每个栈的上限为n/2,如果一个栈元素多于n/2,另一个少于n/2,那么第二种方式栈溢出,第一种方式可以存储。因此,下面实现方式1.
template <class T>
class DoubleStack {
private:
T *p;
int sp1,sp2;
int size1,size2;
int totalLength;
public:
DoubleStack(int n) {
totalLength = n;
p = new T[n];
sp1 = 0;
sp2 = n-1;
size1 = 0;
size1 = 0;
}
~DoubleStack() {
delete [] p;
}
void pushLift(const T & item);
void pushRight(const T & item);
void popLift();
void popRigth();
};
void DoubleStack::pushLift(const T & item) {
if(sp1 == sp2) throw overflow_error;
p[sp1] = item;
sp++;
size1++;
}
void DoubleStack::pushRight(const T & item) {
if(sp1 == sp2) throw overflow_error;
p[sp2] = item;
sp--;
size1++;
}
void DoubleStack::popLift() {
if(sp1 == 0) throw out_of_range;
sp1--;
size1--;
}
void DoubleStack::popLift() {
if(sp2 == totalLength-1) throw out_of_range;
sp2++;
size1--;
}