您的位置:首页 > 编程语言 > C语言/C++

C++链式栈的简单实现(只有基本功能)

2013-09-05 10:38 148 查看
本文用C++简单实现一个链式栈(只有最基本的功能)。代码如下:

List_Stack.h

struct Node {
int value;
Node * next;
};

class List_Stack
{
private:
Node * top;
int size;

public:
List_Stack();
int get_size();
bool is_empty();
int pop();
void push(int value);
};


List_Stack.cpp

List_Stack::List_Stack()
{
top = NULL;
size = 0;
}

int List_Stack::get_size()
{
return size;
}

bool List_Stack::is_empty()
{
if (size == 0)
{
return true;
}
return false;
}

int List_Stack::pop()
{
if (!is_empty())
{
Node * p = top;
int ret = top->value;
top = top->next;

delete p;
p = NULL;
size--;
return ret;
}
else
{
cout << "Error: Stack is empty!" << endl;
return INT_MAX;
}
}

void List_Stack::push(int value)
{
Node * p = new Node;
p->value = value;
p->next = top;
top = p;
p = NULL;
size++;
}


经测试,可行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: