C++|int 배열을 사용하여 스택 클래스를 구현하고 이 스택 클래스에 getMaxValue 메서드를 추가합니다.

인터뷰 질문들:

int 배열을 사용하여 스택 클래스를 구현하고 이 스택 클래스에 getMaxValue 메서드를 추가합니다.

방법:
구현된 스택 클래스에서 스택에 푸시될 때 최대값을 초과한 모든 숫자를 저장하기 위해 하위 스택을 유지합니다.
예를 들어 스택: 3 2 5 1 2 4
, 유지되는 하위 스택은 다음을 저장합니다: 3 5

예를 들어 스택이 3 3 2 5 1 2 4 인 경우
유지 관리되는 하위 스택에는 3 3 5가 저장됩니다.

#include<iostream>
#include<algorithm>
using namespace std;

class Stack {
    
    

public:
	int* data;
	int capacity;
	int top;
	Stack* maxRecord;

	Stack():Stack(true) {
    
    

	}

	
	~Stack() {
    
    
		if (maxRecord->is_empty()) {
    
    
			delete maxRecord;
		}
		delete[] data;
	}

	void push(int item) {
    
    
		if (top == capacity - 1) {
    
    
			expand_capacity();
		}
		data[++top] = item;

		//add max
		if (maxRecord) {
    
    
			if (maxRecord->is_empty()) {
    
    
				maxRecord->push(item);
			}
			else {
    
    
				if (item >= maxRecord->getTop()) {
    
    
					maxRecord->push(item);
				}
			}
		}
	}

	int pop() {
    
    
		if (!is_empty()) {
    
    
			//pop max
			if (maxRecord) {
    
    
				if (!maxRecord->is_empty()) {
    
    
					if (maxRecord->getTop() == getTop()) {
    
    
						maxRecord->pop();
					}
				}
			}
			return data[top--];
		}
		else {
    
    
			throw runtime_error("Stack is empty");
		}

	}

	int getTop() {
    
    
		if (!is_empty()) {
    
    
			return data[top];
		}
		else {
    
    
			throw std::runtime_error("Stack is empty");
		}
	}

	bool is_empty() {
    
    
		return top == -1;
	}

	int size() {
    
    
		return top + 1;
	}
	int getMaxValue() {
    
    
		if (maxRecord) {
    
    
			if (!maxRecord->is_empty()) {
    
    
				return maxRecord->getTop();
			}
			else {
    
    
				cout << "empty" << endl;
			}
		}
	}

	void expand_capacity() {
    
    
		int new_capacity = capacity * 2;
		int* new_data = new int[new_capacity];
		for (int i = 0; i <= top; ++i) {
    
    
			new_data[i] = data[i];
		}
		delete[] data;
		data = new_data;
		capacity = new_capacity;
	}
private:
	Stack(bool need) {
    
     //将有参构造隐藏
		capacity = 2;
		data = new int[capacity];
		top = -1;
		if (need) {
    
    
			maxRecord = new Stack(!need); //防止递归创建
		}
		else {
    
    
			maxRecord = nullptr;
		}
	}

};

int main()
{
    
    
	Stack stack;
	stack.push(2);
	stack.push(1);
	stack.push(3);
	stack.push(3);
	stack.push(2);
	stack.push(5);

	cout << "Stack size: " << stack.size() << endl;
	cout << "MaxValue: " << stack.getMaxValue() << endl;
	stack.pop();
	cout << "MaxValue: " << stack.getMaxValue() << endl;
	stack.pop();
	cout << "MaxValue: " << stack.getMaxValue() << endl;
	stack.pop();
	cout << "MaxValue: " << stack.getMaxValue() << endl;
	stack.pop();
	cout << "MaxValue: " << stack.getMaxValue() << endl;

	return 0;
}

Guess you like

Origin blog.csdn.net/holly_Z_P_F/article/details/132460795