链栈C++实现

LinkStack.h

#pragma once
#ifndef LINKSTACK_H
#define LINKSTACK_H

#include
#include
using std::cout;
using std::cin;
using std::endl;
using std::ostream;
template  class linkStack;

template
class Node
{
public:
	Node(Node*ptr=nullptr):next(ptr){}
	T data;//栈的数据
	Node* next;	
};


template
class linkStack
{
public:
	linkStack();
	~linkStack();
	void push(const T& elem);//进栈
	void pop(T& elem);//出栈
	bool empty();//查看栈是否为空
	int getSize();//返回栈中元素的个数
	void clearStack();//清空栈中的元素
	void print();//打印栈中的元素
	bool getTop(T &elem);//读取栈顶元素

	template
	friend ostream& operator<<(ostream& os, linkStack& l);

private:
	Node *top;//定义栈顶指针
};

template
linkStack::linkStack(){
	Node* p = (Node*)new Node[1];
	top = p;
	top->next = nullptr;
}

template
linkStack::~linkStack(){
	Node* p = top;
	Node* q = nullptr;
	while (p->next!=nullptr){
		q = p;
		p = p->next;
		delete q;
	}
	if (q == nullptr)
		delete q;
	delete p;
}

//进栈
template
void linkStack::push(const T& elem){
	Node* p = (Node*)new Node[1];
	p->data = elem;
	Node* q;
	if (!empty()){		
		q = top->next;
		top->next = p;
		p->next = q;
	}
	else
		top->next = p;
}

//出栈
template
void linkStack::pop(T& elem){
	if (!empty()){
		Node* p = top->next;
		elem = p->data;
		top->next = p->next;
		//cout <<"移除元素为:"<
bool linkStack::empty(){
	if (top->next != nullptr)
		return false;
	return true;
}

//返回栈中元素的个数
template
int linkStack::getSize(){
	int Index = 0;
	Node* p = top->next;
	while (p) {//当p节点不为零时
		p = p->next;
		++Index;
	}
	return Index;
}

//清空栈中的元素
template
void linkStack::clearStack(){
	if (!empty()){
		Node* p = top->next;
		Node* q;
		while (p){
			q = p;
			p = p->next;
			delete q;
		}
		if (q == nullptr)
			delete q;
		delete p;
	}
	top->next = nullptr;
}

//打印栈中的元素
template
void linkStack::print(){
	Node* p = top->next;
	while (p){
		cout << p->data << " ";
		p = p->next;
	}
	cout << endl;
}

//读取栈顶元素
template
bool linkStack::getTop(T&elem){
	Node* p = top->next;
	if (p) {
		elem = p->data;
		return true;
	}
	else {
		cout << "栈为空" << endl;
		return false;
	}

}


template
ostream& operator<<(ostream& os, linkStack& l) {
	os << "栈中元素个数为:" << l.getSize() << endl;
	Node* p = l.top->next;
	for (int i = 0; i < l.getSize(); i++){
		os << p->data << " ";
		p = p->next;
	}
	os << endl;
	return os;
}


#endif // !LINKSTACK_H

main.cpp

#include"LinkStack.h"

int main()
{
	linkStack ls;
	int a = 0;
	int b = 0;
	for (int i = 0; i < 10; i++)
	{
		ls.push(i);
	}
	ls.print();
	cout << ls.getTop(b) << " " << b << endl;
	for (int i = 0; ls.empty()==0; i++)
	{
		ls.pop(a);
		cout << a << " ";
		cout << " 循环次数为:" << i + 1 << endl;
	}
	cout << endl;
	cout << ls;
	
}

 

你可能感兴趣的:(链栈C++实现)