資料結構——線性表:順序棧,鏈式棧(C++)
阿新 • • 發佈:2018-12-18
內容概要:
- 棧的基本概念及注意事項
- 順序棧、鏈式棧的C++模板類的實現
棧的基本概念及注意事項:
- 棧(stack)是限定僅在一端進行插入或刪除操作的線性表。
- 與順序表和連結串列一樣,棧分為順序棧和鏈式棧。
- 棧頂(top)元素、入棧(push)、出棧(pop)
圖示:
- 棧廣泛應用於遞迴中,使用棧可以模擬遞迴。
實現程式碼(測試環境VS2017):
//Stack_ADT.h #ifndef STACK_ADT_H #define STACK_ADT_H template<typename E> class Stack { private: void operator =(const Stack&){} Stack(const Stack&){} public: Stack(){} virtual ~Stack(){} virtual void clear() = 0; virtual void push(const E&it) = 0; virtual E pop() = 0; virtual const E& topValue() const = 0; virtual int length() const = 0; }; #endif // !STACK_ADT_H
//array_based_stack.h #ifndef ARRAY_BASED_STACK_H #define ARRAY_BASED_STACK_H #include<assert.h> #include"Stack_ADT.h" template<typename E> class AStack :public Stack<E> { private: int maxSize; int top; E*listArray; public: AStack(int size = 100)//default size 100 { maxSize = size; top = 0; listArray = new E[size]; } ~AStack() { delete[]listArray; } void clear() { top = 0; } void push(const E& it) { assert(top != maxSize);//stack is full listArray[top++] = it; } E pop() { assert(top != 0);//stack is empty return listArray[--top]; } const E& topValue() const { assert(top != 0);//stack is empty return listArray[top - 1]; } int length() const{ return top; } }; #endif // !ARRAY_BASED_STACK_H
//linked_stack.h
#ifndef LINKED_STACK_H
#define LINKED_STACK_H
#include"Stack_ADT.h"
template<typename E>
class SLink
{
public:
E element;
SLink*next;
//兩個建構函式
SLink(const E&elemval, SLink*nextval = NULL){ element = elemval; next = nextval; }
SLink(SLink*nextval = NULL) { next = nextval; }
};
template<typename E>
class LStack :public Stack<E>
{
private:
SLink<E>*top;
int size;
public:
LStack(int s = 100)//default size 100, no use
{
top = NULL;
size = 0;
}
~LStack() { clear(); }
void clear()
{
while (top != NULL)
{
SLink<E>*temp = top;
top = top->next;
delete temp;
}
size = 0;
}
void push(const E&it)
{
top = new SLink<E>(it, top);
size++;
}
E pop()
{
assert(top != NULL);//stack is empty
E it = top->element;
SLink<E>*ltemp = top->next;
delete top;
top = ltemp;
size--;
return it;
}
const E& topValue() const
{
assert(top != NULL);//stack is empty
return top->element;
}
int length() const { return size; }
};
#endif // !LINKED_STACK_H
//《資料結構與演算法分析(第三版)P76-P81》
//main.cpp
#include<iostream>
#include"array_based_stack.h"
#include"linked_stack.h"
using namespace std;
int main()
{
//test place
system("pause");
}
轉載請註明出處:https://blog.csdn.net/Hodge_Z/article/details/85063143