链栈 讲义实现

#include <iostream>
using namespace std;

typedef int Status;

const int OK = 1;
const int ERROR = 0;

template <class T>
struct Node
{
	T data;
	Node<T> *next;
};

template <class T>
class LinkStack
{
public:
	LinkStack();
	~LinkStack();
	Status Push(T e);
	Status Pop(T &e);
	Status GetTop(T &e);
	int StackLength();
	Status IsEmpty();
	void DispStack();

private:
	Node<T> *top;
};

template <class T>
LinkStack<T>::LinkStack()
{
	top = new Node<T>;
	top->next = nullptr;
}

template <class T>
LinkStack<T>::~LinkStack()
{
	Node<T> *p = top;
	while(p != NULL)
	{
		p = p->next;
		delete top;
		top = p;
	}
}
//入栈操作
//相当于头插法
template <class T>
Status LinkStack<T>::Push(T e)
{
	Node<T> *p = new Node<T>;
	if(p == NULL)
	{
		return ERROR;
	}
	p->data = e;
	p->next = top->next;
	top->next = p;
	return OK;
}

//出栈
template <class T>
Status LinkStack<T>::Pop(T &e)
{
	Node<T> *p;
	if(top->next == NULL)
	{
		return ERROR;
	}
	p = top->next;
	e = p->data;
	top->next = p->next;
	delete p;
	return OK;
}

template <class T>
void LinkStack<T>::DispStack()
{
	Node<T> *p = NULL;
	if(top->next == NULL)
	{
		return;
	}
	p = top->next;
	while(p != NULL)
	{
		cout<< p->data << " ";
		p = p->next;
	}
	cout<< endl;
}

template <class T>
Status LinkStack<T>::GetTop(T &e)
{
	if(top->next == NULL)
	{
		return ERROR;
	}
	e = top->next->data;
	return OK;
}

template <class T>
int LinkStack<T>::StackLength()
{
	Node<T> *p = top->next;
	int cnt = 0;
	while(p != NULL)
	{
		cnt++;
		p = p->next;
	}
	return cnt;
}

template <class T>
Status LinkStack<T>::IsEmpty()
{
	return (top->next == NULL)? OK:ERROR;
}
int main()
{
	LinkStack<int> stack1;
	for(int i=0; i<10; i++)
	{
		stack1.Push(i);
	}
	stack1.DispStack();
	int temp = 0;
	for(int i=0; i<10; i++)
	{
		stack1.Pop(temp);
		cout<< temp << " ";
	}
	cout<< endl;
	cout << "**************" << endl;
	stack1.DispStack();
	cout<< stack1.IsEmpty()<<endl;
	cout << "***************"<<endl;
	temp = 4;
	stack1.GetTop(temp);	//temp的值并没有改变
	cout << temp <<endl;
	for(int i=0; i<10; i++)
	{
		stack1.Push(i);
	}
	stack1.DispStack();
	stack1.GetTop(temp);
	cout<< temp << endl;
	cout << "链栈长为:" << stack1.StackLength()<<endl;
	stack1.Pop(temp);
	cout<<temp <<endl;
	cout << "链栈长为:" << stack1.StackLength()<<endl;
	cout<< stack1.IsEmpty()<<endl;
	return 0;
}

测试结果

猜你喜欢

转载自blog.csdn.net/HdUIprince/article/details/82941566