Tips:此栈栈内数据为 int 型。
//10:13:2015 by tracelessspring
struct Node {
int data;
Node *next;
};
class linkstack {
private:
Node *first;
public:
linkstack() {
first = NULL;
}
~linkstack() {
makeEmpty();
}
void push(int x) { //其实push的实现方式很重要,它决定了你的链表的组织方式,从而决定了链表的各种特性,进而影响了后面各个函数如pop,gettop等等的实现。
Node *node = new Node;
node->data = x;
node->next = first;
first = node;
}
void pop(int &x) {
if (first == NULL)
{
cout << "the stack is empty" << endl;
exit(0);
}
x = first->data;
Node *temp = first;
first = first->next;
delete temp;
}
int gettop() {
return first->data;
}
bool isempty() {
return first == NULL;
}
int getsize() {
int size = 0;
Node *temp = first;
while (temp != NULL)
{
size++;
temp = temp->next;
}
return size;
}
void makeEmpty() {
while (first != NULL)
{
Node *temp = first;
first = first->next;
delete temp;
}
}
void printelement() {
Node *temp = first;
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};