c++ 语言程序设计(第四版)郑莉 用链表实现栈

c++ 语言程序设计(第四版)郑莉 用链表实现栈

仿照着教材中用数组实现栈的程序写了一个用链表实现的栈,与原来的栈接口一样,可以用此Stack.h直接替换原来的文件运行计算器的程序,不过得把之前的"LinkedList.h"和"Node.h"添加到工程中。
不过我并没有检验这个栈的其他功能,没用验证别的逻辑错误,只是测试了一些简单的计算器的功能。水平有限,如果有错误还请指正,谢谢!

//Stack.h
//
// Created by LYH on 2020/6/20.
//

#ifndef STACK_H
#define STACK_H

#include <cassert>
#include "LinkedList.h"

template<class T , int SIZE = 50>
class Stack{
private:
    LinkedList<T> list;
    int top;
public:
    Stack();
    void push(const T &item);
    T pop();
    void clear();
    const T &peek() const;
    bool isEmpty() const;
    bool isFull() const;
};


template<class T , int SIZE>
Stack<T,SIZE>::Stack():top(-1) { }
//压栈和弹栈都是在链表的Front进行的
template<class T , int SIZE>
void Stack<T,SIZE>::push(const T &item) {
    assert(!isFull());
    list.insertFront(item);
    top++;
}

template<class T , int SIZE>
T Stack<T,SIZE>::pop(){
    assert(!isEmpty());
    list.reset();
    T temp=list.data();
    list.deleteFront();
    top--;
    return temp;
}

template<class T,int SIZE>
void Stack<T,SIZE>::clear(){
    top=-1;
    while(!list.isEmpty()){
        list.deleteFront();
    }
}

template<class T,int SIZE>
const T &Stack<T,SIZE>::peek() const{
    //list.reset();//保证链表的指针一直是在Front,与const冲突,注释后不影响
    return list.data();
}

template<class T , int SIZE>
bool Stack<T,SIZE>::isEmpty() const {
    return top == -1;
}

template<class T,int SIZE>
bool Stack<T,SIZE>::isFull() const {
    return top == SIZE - 1;
}
#endif //STACK_H

猜你喜欢

转载自blog.csdn.net/lslfox/article/details/106888528