//LinkNode.h
#ifndef LINKNODE_H
#define LINKNODE_H
#include
using namespace std;
template
class LinkNode{
public:
T data;
LinkNode
* link;
LinkNode(){
}
LinkNode(T value, LinkNode
* str = NULL) :data(value), link(str){
}
};
#endif
//StackList.h
#ifndef STACKLIST_H
#define STACKLIST_H
#include"LinkNode.h"
#include
#include
#include
using namespace std; template
class StackList{ private: LinkNode
* topStack; //该程序所表达的链表不含头结点 public: StackList();//默认构造函数 StackList(const StackList
& str);//拷贝构造函数 ~StackList(); void Clear(); void Push(const T value); void Pop();//删除栈顶元素 T Top();//返回栈顶元素,但不删除 bool isEmpty()const; T TopAndPop();//返回栈顶元素并删除 int Length();//返回栈的长度 void Print(); void Sort(); }; template
StackList
::StackList() { //默认构造函数 //因为该链表不含头结点,所以在默认构造函数中不生成栈顶节点 } template
StackList
::StackList(const StackList
& str) { LinkNode
* p = str.topStack; if (p != NULL) { topStack = new LinkNode
(p->data); } else return; LinkNode
* pHead = topStack; p = p->link; while (p) { topStack->link = new LinkNode
(p->data); p = p->link; topStack = topStack->link; } topStack->link = NULL; topStack = pHead; } template
StackList
::~StackList() { Clear(); } template
void StackList
::Clear() { LinkNode
* p = topStack; while (p) { p = p->link; delete topStack; topStack = p; } } template
void StackList
::Push(const T value) { LinkNode
* p = new LinkNode
(value); p->link = topStack; topStack = p; } template
void StackList
::Pop() { if (topStack == NULL) return; LinkNode
* p = topStack->link; delete topStack; topStack = p; } template
T StackList
::Top() { if (topStack == NULL) return 1; T data = topStack->data; return data; } template
bool StackList
::isEmpty()const { if (topStack == NULL) return true; else return false; } template
T StackList
::TopAndPop() { T data = Top(); Pop(); return data; } template
int StackList
::Length() { int Count = 0; LinkNode
*p = topStack; while (p) { p = p->link; Count++; } return Count; } template
void StackList
::Print() { LinkNode
* p = topStack; while (p) { cout << p->data << " "; p = p->link; } cout << endl; } template
void StackList
::Sort() { vector
vec; LinkNode
* p = topStack; while (p) { vec.push_back(p->data); p = p->link; } p = topStack; sort(vec.begin(),vec.end()); vector
::const_iterator iter = vec.begin(); for (; iter != vec.end(); iter++) { p->data = *iter; p = p->link; } } #endif //主函数 #include"StackList.h" int main(int argc, char argv[]) { StackList
list; list.Push(5); list.Push(4); list.Push(2); list.Push(3); list.Push(1); list.Push(0); list.Push(9); list.Push(7); list.Print(); int value = list.Top(); cout << "栈顶元素:" << value << endl; list.Pop(); list.Print(); list.Sort(); list.Print(); int temp = list.Top(); cout << "栈顶元素:" << temp << endl; return 0; }
一连浪了好几天了,一直没好好的学习,希望在运动会结束后能够好好的认真学习,下面是关于栈的链表形式的有关函数的实现,与上一个实现形式有所差别
最新推荐文章于 2022-09-12 10:53:58 发布