c++链栈

hpp

#pragma once
#include<iostream>
#include<string>
using namespace std;
template<class T>
struct StNode
{
public:
	T data;
	StNode<T>* next;
};
template<class T>
class LinkStack
{
private:
	//栈顶指针
	StNode<T>* top;
public:
	LinkStack();
	LinkStack(LinkStack& ls);
	~LinkStack();
	int Length();
	bool empty();
	void clear();
	bool push(T e);
	bool pop(T &e);
	bool getTop(T& e);
};

cpp

#include"链栈.hpp"
#include<iostream>
#include<string>
using namespace std;

template<class T>
LinkStack<T>::LinkStack()
{
	this->top = NULL;
}
template<class T>
LinkStack<T>::LinkStack(LinkStack& st)
{
	StNode<T>* p,*q,*pre;
	p = new StNode<T>;
	this->top = p;
	q = st.top;
	while (q != NULL)
	{
		pre = new StNode<T>;
		p->next = pre;
		p->data = q->data;
		p = pre;
		delete pre;
		q = q->next;
	}
	p->next = NULL;
}
template<class T>
LinkStack<T>::~LinkStack()
{
	cout << "调用析构函数" << endl;
	StNode<T>* p;
	while (top != NULL)
	{
		p = top;
		top = p->next;
		delete p;
	}
}
template<class T>
int LinkStack<T>::Length()
{
	int count = 0;
	StNode<T>* p;
	p = this->top;
	while (p != NULL)
	{
		p = p->next;
		count++;
	}
	return count;
}
template<class T>
bool LinkStack<T>::empty()
{
	return this->top == NULL;
}
template<class T>
void LinkStack<T>::clear()
{
	StNode<T>* p;
	while (top != NULL)
	{
		p = top;
		top = top->next;
		delete p;
	}
}
template<class T>
bool LinkStack<T>::push(T e)
{
	StNode<T>* p = new StNode<T>;
	p->next = top;
	top = p;
	p->data = e;
	return true;
}
template<class T>
bool LinkStack<T>::pop(T& e)
{
	if (top == NULL)
	{
		return false;
	}
	StNode<T>* old_Top;
	old_Top = top;
	e = this->top->data;
	top = top->next;
	delete old_Top;
	return true;
}
template<class T>
bool LinkStack<T>::getTop(T& e)
{
	if (top == NULL)
		return false;
	e = top->data; 
	return true;
}
int main()
{
	LinkStack<int>a;
	for (size_t i = 0; i < 5; i++)
	{
		a.push(i);
	}
	LinkStack<int>b(a);
	int t;
	b.getTop(t);
	//int t;
	//t = a.Length();
	a.getTop(t);
	//a.clear();
	//t = a.Length();
	cout << t << endl;
	system("pause");
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值