之前一直都是用c语言实现的链表,今天看到c++实现的链表,不禁跃跃欲试,虽然参考着书,但是也是半脱稿,能自己码多少就码多少,日后再重新码一边。话说c++是真的适合用来描述数据结构。
LStack.h:
#pragma once
#include<assert.h>
template<class T>class LStack;//事先声明一波,为了创建友元类
template<class T>class Node {
friend class LStack<T>;
private :
T data;
Node<T> *link;//和c语言数据结构定义很相似
public:
Node(T d=0,Node <T>*next=NULL):data(d),link(next){}
};
template<class T>class LStack {
private:
Node <T> *top;
public:
LStack():top(nullptr){}
~LStack(){ MakeEmpty(); }
bool Push(T &x);
bool Pop(T &x);
bool GetTop(T &x);//没有编写GetTop,没啥好写的
void MakeEmpty();
bool IsEmpty() { return (top == NULL) ? true : false; }
int GetSize()const;
};
template<class T>
bool LStack<T>::Push(T &x) {
top = new Node<T>(x, top);
assert(top != nullptr);//头文件<assert.h>,为了提高程序的容错
return true;
}
template<class T>
void LStack<T>::MakeEmpty() {
Node<T> *p;
while(top!=nullptr)//注意这个地方要用nullptr而不是null,如果用null会提示报错
{
p = top;
top = top->link;
delete p;
}
}
template <class T>
bool LStack<T>::Pop(T &x) {
if (IsEmpty()==true)return false;
Node<T> *p = top;
x = top->data;
top = top->link;
delete p;
return true;
}
template<class T>
int LStack<T>::GetSize()const {
int count = 0;
Node<T> *p = top;
while (p != nullptr) {
p = p->link;
count++;
}
return count;
}
main函数测试程序:
#include"LStack.h"
#include<iostream>
using namespace std;
int main() {
int x = 10,y;
LStack<int> s;
for (int i = 0; i < 5;i++)
s.Push(x);
s.Pop(y);
cout <<"element"<< y << endl;
cout <<"size:"<< s.GetSize() << endl;
}
附录:友元类的介绍:
友元类的所有成员函数都是另一个类的友元函数,都可以访问另一个类中的隐藏信息(包括私有成员和保护成员)。当希望一个类可以存取另一个类的私有成员时,可以将该类声明为另一类的友元类。
关于友元类的注意事项:
(1) 友元关系不能被继承。
(2) 友元关系是单向的,不具有交换性。若类B是类A的友元,类A不一定是类B的友元,要看在类中是否有相应的声明。
(3) 友元关系不具有传递性。若类B是类A的友元,类C是B的友元,类C不一定是类A的友元,同样要看类中是否有相应的申明。
摘自某博客