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

本文用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++;
}

经测试,可行。

你可能感兴趣的:(C++,栈,基本数据结构)