[C ++] linkedStackクラスの実装

linkedStack.h:

#pragma once
#include"chainNode.h"
#include<iostream>
using namespace std;
template<class T>
class linkedStack
{
    
    
private:
	chainNode<T>* stackTop;//栈顶指针
	int stackSize;		//栈中元素个数
public:
	linkedStack(int initialCapacity = 10)
	{
    
    
		stackTop = NULL;
		stackSize = 0;
	}
	~linkedStack();

	bool empty()const {
    
    
		return stackSize == 0;
	}
	int size()const {
    
    
		return stackSize;
	}
	void pop();
	void push(const T& theElement) {
    
    
		stackTop = new chainNode<T>(theElement, stackTop);
		stackSize++;
	}
	T& top()const {
    
    
		return stackTop->element;
	}

};

template<class T>
inline linkedStack<T>::~linkedStack()
{
    
    
	while (stackTop != NULL)
	{
    
    
		chainNode<T>* nextNode = stackTop->next;
		delete stackTop;
		stackTop = nextNode;
	}
}

template<class T>
inline void linkedStack<T>::pop()
{
    
    
	if (empty()) {
    
    
		cout << "栈为空,无法出栈";
		return;
	}
	else {
    
    
		chainNode<T> *nextNode = stackTop->next;
		delete stackTop;
		stackTop = nextNode;
		stackSize--;
	}
}

Test.cpp:

#include<iostream>
using namespace std;
#include"linkedStack.h"
int main() {
    
    
    linkedStack<int> s;

    // add a few elements
    s.push(1);
    s.push(2);
    s.push(3);
    s.push(4);

    cout << "Stack should be 1234, bottom to top" << endl;

    // test empty and size
    if (s.empty())
        cout << "The stack is empty" << endl;
    else
        cout << "The stack is not empty" << endl;

    cout << "The stack size is " << s.size() << endl;

    while (!s.empty())
    {
    
    
        cout << "Stack top is " << s.top() << endl;
        s.pop();
        cout << "Popped top element" << endl;
    }
    s.pop();
	return 0;
}


ここに画像の説明を挿入

おすすめ

転載: blog.csdn.net/weixin_48180029/article/details/113418354