直接先贴代码
LinkStack.h:
#pragma once
template <class DataType>
struct Node {
DataType data;
Node<DataType>* next;
};
template <class DataType>
class LinkStack
{
private:
Node<DataType>* top;
public:
LinkStack();
~LinkStack();
void push(DataType x);
DataType pop();
DataType getTop();
bool isEmpty();
};
LinkStack.cpp:
#include <iostream>
#include "LinkStack.h"
using namespace std;
template <class DataType>
LinkStack<DataType>::LinkStack()
{
top = NULL;
}
template <class DataType>
LinkStack<DataType>::~LinkStack()
{
while (top!=NULL)
{
Node<DataType>* p = top;
top = top->next;
delete p;
p = NULL;
}
delete top;
top = NULL;
}
template <class DataType>
void LinkStack<DataType>::push(DataType x)
{
//先准备好一个节点 然后指向原来的节点,然后再把top指针上移
Node<DataType>* s = new Node<DataType>;
s->data = x;
s->next = top;
top = s;
}
template <class DataType>
DataType LinkStack<DataType>::pop()
{
if (top == NULL)
return -1;
char x = top->data;
Node<DataType>* p = top; //先创造一个指针指向原来的top
top = top->next;
delete p;
p = NULL; //记得设空
return x;
}
template <class DataType>
DataType LinkStack<DataType>::getTop()
{
return top->data;
}
template <class DataType>
bool LinkStack<DataType>::isEmpty()
{
if (top == NULL) {
return true;
}
else
{
return false;
}
}
//主函数入口
int main()
{
std::cout << "Hello World!\n";
LinkStack<char> s1;
s1.push('a');
s1.push('b');
s1.push('c');
cout << "出来的是" << s1.pop() << endl;
cout << "出来的是" << s1.pop() << endl;
cout << "出来的是" << s1.pop() << endl;
system("pause");
return 0;
}
大概就实现了一些链栈最基本的功能,下一步用这个链栈去做一个DFS迷宫路径问题。
不足之处,希望大家多多指教。