c++实现简单顺序栈与链栈
栈作为数据结构线性结构的一部分,栈的实现相对来说比较简便。本质上,顺序栈是顺序表的子集,链栈是链表的子集。在我看来,栈的实现无非是在类中留出更少的接口:只有尾插,尾删,获取top等几种。其稍稍与表的不同是栈是先进后出。即通过一个游动的top指针(顺序栈中用int top来表示数组中的成员位置)来进行对栈的操作。而表中无论是头指针还是尾指针都不动。下面给出实现代码,顺序依次为:顺序栈,链栈和测试。
SeqStack.hpp
#include <iostream>
using namespace std;
const int StackSize=1024;
template <class T>
class SeqStack
{
public:
SeqStack() { this->top = -1; };
void Push(T data);
void Pop();
T GetTop();
bool IsEmpty() { return top == -1 ? true : false; };
void StackPrint();
private:
T arr[StackSize];
int top;
};
template <class T>
void SeqStack<T>::Push(T data)
{
if (top >= StackSize - 1)
{
cout << "栈已满" << endl;
}
else
{
top++;
this->arr[top]=data;
}
return;
}
template <class T>
void SeqStack<T>::Pop()
{
if (top == -1)
{
cout << "栈空" << endl;
}
else
{
top--;
}
}
template <class T>
T SeqStack<T>::GetTop()
{
if (top == -1)
{
cout << "栈空" << endl;
return -1;
}
else
{
return this->arr[top];
}
}
template <class T>
void SeqStack<T>::StackPrint()
{
int p = top;
while (p!= -1&&p>=0)
{
cout << this->arr[p]<<" ";
p--;
}
cout << endl;
}
LinkStack.hpp
#include <iostream>
using namespace std;
template <class T>
class Node
{
public:
T data;
Node* next;
};
template <class T>
class LinkStack
{
public:
LinkStack(){top = NULL;};
~LinkStack()
{
Node<T>* p = top;
while (p)
{
top = p;
p = p->next;
delete top;
}
};
void Push(T data)
{
Node<T>* temp = new Node<T>;
temp->data = data;
temp->next = top;
top = temp;
}
void Pop()
{
Node<T>* p = top;
p = p->next;
delete top;
top = p;
}
void LSPrint()
{
Node<T>* p = top;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
T GetTop()
{
if (top != NULL)
{
return top->data;
}
else
{
return -1;
}
}
bool IsEmpty() { return (top == NULL) ? true : false; };
private:
Node<T>* top;
};
栈测试.cpp
#include <iostream>
using namespace std;
#include "SeqStack.hpp"
#include "LinkStack.hpp"
int main()
{
SeqStack<int> SS;
SS.Push(1);
SS.Push(2);
SS.Push(3);
SS.StackPrint();
SS.Pop();
SS.StackPrint();
cout<<"getTop = "<<SS.GetTop()<<endl;
LinkStack<int>LS;
LS.Push(4); LS.Push(5); LS.Push(6);
LS.LSPrint();
LS.Pop();
LS.LSPrint();
cout << "getTop = " << LS.GetTop() << endl;
system("pause");
return 0;
}
测试结果: