[数据结构]栈的实现-C++

栈用两种方法实现,一种是链表,一种是数组



栈使用数组实现:


//StackBaseArray.h

#pragma once

template <class T>
class StackBaseArray {
private:
	T *array;
	int maxLength=1;
	int top;
public:
	StackBaseArray();
	StackBaseArray(int maxLength);
	bool push(T value);
	T pop();
	T peek();
	bool clear();
	bool isEmpty();
};


//StackBaseArray.cpp

#include"StackBaseArray.h"

template <class T> StackBaseArray<T>::StackBaseArray() {
	maxLength = 64;
	array = new T[64];
	top = -1;
}

template <class T> StackBaseArray<T>::StackBaseArray(int maxLength) {
	this->maxLength = maxLength;
	array = new T[maxLength];
	top = -1;
}

template <class T> bool StackBaseArray<T>::push(T value) {
	if (top == maxLength - 1) {
		return false;
	}
	top++;
	array[top] = value;
	return true;
}

template <class T> T StackBaseArray<T>::pop() {
	if (top == -1) {
		return NULL;
	}
	top--;
	return array[top + 1];
}

template <class T> T StackBaseArray<T>::peek() {
	if (top == -1) {
		return NULL;
	}
	return array[top];
}

template <class T> bool StackBaseArray<T>::clear() {
	top = -1;
	return true;
}

template <class T> bool StackBaseArray<T>::isEmpty() {
	if (top == -1) {
		return true;
	}
	else {
		return false;
	}
}


栈使用链表实现

//StackBaseLinkedList.h

#pragma once

template <class T>
struct Node {
	T value;
	Node *next;
};

template <class T>
class StackBaseLinkedList {
private:
	Node<T> *head;
public:
	StackBaseLinkedList();
	bool push(T value);
	T pop();
	T peek();
	bool clear();
	bool isEmpty();
};


//StackBaseLinkedList.cpp

#include"StackBaseLinkedList.h"

template <class T> StackBaseLinkedList<T>::StackBaseLinkedList() {
	head = NULL;
}

template <class T> bool StackBaseLinkedList<T>::push(T value) {
	if (head == NULL) {
		head = new Node<T>;
		head->value = value;
		head->next = NULL;
	}
	else {
		Node<T> *n = new Node<T>;
		n->value = value;
		n->next = head;
		head = n;
	}
	return true;
}

template <class T> T StackBaseLinkedList<T>::pop() {
	if (head == NULL) {
		return NULL;
	}
	else {
		T value = head->value;
		head = head->next;
		return value;
	}
}

template <class T> T StackBaseLinkedList<T>::peek() {
	if (head == NULL) {
		return NULL;
	}
	else {
		return head->value;
	}
}


template <class T> bool StackBaseLinkedList<T>::clear() {
	head = NULL;
	return true;
}

template <class T> bool StackBaseLinkedList<T>::isEmpty() {
	if (head == NULL) {
		return true;
	}
	else {
		return false;
	}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值