2012-10-16 21:40:05Morris
[資料結構][作業] STACK 實作
前言:
以C or C++完成
請以Link list來實作一個大小為5的Stack
必須包含Push Pop(含印出) Isfull Isempty功能
一個功能占25pt
繳交格式 學號_姓名_HW1.cpp (ex: 1005XXXXX_助教_HW1.cpp)
檔案只需要.cpp or .c 檔 不需要其他檔案
有問題再寄信給助教
雖然是這麼說, 我基本上還是按照 STL 中的 Stack 去實作其方法。
#include <cstdlib>
using namespace std;
template <typename T>
struct Node {
T d;
Node *prev;
};
template <class T>
class STACK {
public:
STACK() {
idx = NULL;
SIZE = 0;
}
T top() {
if(isempty()) {
puts("top() cant't access !!");
exit(1);
}
T cpy = idx->d;
return cpy;
}
void pop() {
if(isempty()) {
puts("pop() can't access !!");
return;
}
Node<T> *tmp;
tmp = idx;
idx = idx->prev;
delete tmp;
SIZE--;
}
void push(T item) {
if(isfull()) {
puts("push() can't access !!");
return;
}
Node<T> *nd = new Node<T>;
nd->d = item;
nd->prev = idx;
idx = nd;
SIZE++;
}
bool isempty() {
return idx == NULL;
}
bool isfull() {
return SIZE == 5;
}
int size() {
return SIZE;
}
private:
Node<T> *idx;
int SIZE;
};
int main() {
STACK<int> stk;
int cmd, ins;
while(printf("[0]pop [1]push [2]isfull [3]isempty [4]top : "),
scanf("%d", &cmd) == 1) {
switch(cmd) {
case 0:
stk.pop();
break;
case 1:
printf("please enter a integer : "), scanf("%d", &ins);
stk.push(ins);
break;
case 2:
printf("%s\n", stk.isfull() ? "true" : "false");
break;
case 3:
printf("%s\n", stk.isempty() ? "true" : "false");
break;
case 4:
printf("%d\n", stk.top());
}
}
return 0;
}