1. 程式人生 > >騰訊面試題:模板實現一個棧,要求Push(入棧),Pop(出棧),Max(返回最大值的操作)的時間複雜度為O(1)

騰訊面試題:模板實現一個棧,要求Push(入棧),Pop(出棧),Max(返回最大值的操作)的時間複雜度為O(1)

解題思路:要用模板實現亂序入棧的陣列每次pop()出棧都能得到當前棧中Max的最大值,就必須在push()入棧時進行維護操作,使的每次入棧的元素都能夠找到合適的位置並push(),每次push()操作完成後棧中的元素都能夠按從棧頂到棧底從大到小排列即可。這就需要寫一個不同於常規操作的maxpush()函式,用兩個棧s1、s2就可以實現此功能,maxpush()操作時,如果為空就直接push()元素給s1,當s1不為空時,獲取當前s1的棧頂元素Temp與即將要入棧的元素item進行比較,如果Temp<=item則直接push()壓棧,如果Temp>item時,將s1的棧頂元素壓入s2中直到s1的棧頂元素Temp<=item或者s1為空時再將item壓入s1,並將s2中的元素pop()出來逐一壓入s1中,這樣每次maxpush()時進行s1棧的維護,就能使得s1棧每次pop()都能夠獲取當前棧中的最大元素。

c++模板順序棧實現原始碼:

#include<iostream>
using namespace std;
/*
用模板實現一個push()方法和一個pop方法,求出該棧中的max;
*/
template<typename T>
class SeqStack
{
public:
	SeqStack(int sz) :Top(-1), MaxSize(sz)
	{
		Element = new T[sz];
		if (Element == NULL)
		{
			cout << "Application Error!" << endl;
			exit(1);
		}
	}
	~SeqStack()
	{
		delete[] Element;
	}

public:
	void Push(const T item); //push data
	void MaxStackPush(const T &item,int Len);
	T Pop();                 //pop data
	T GetTop() const;        //get data
	void Print();            //print the stack
	void MakeEmpty()	     //make the stack empty
	{
                Top = -1;
        }
	bool IsEmpty() const    //judge stack whether empty
	{
		return Top == -1;
        }
	bool IsFull() const    //judge stack whether full
	{
		return Top == MaxSize - 1;
	}
private:
	int Top; //
	T *Element;
	int MaxSize;
};

template<typename T>
void SeqStack<T>::Push(const T item)
{
	if (IsFull())
	{
		cout << "The stack is full!" << endl;
		return;
	}
	Element[++Top] = item;
}

template<typename T>
void SeqStack<T>::MaxStackPush(const  T &item,int Len)
{
	SeqStack <T> s1(Len);
	if (IsEmpty())
	{
		Push(item);
	}
	else if (!IsEmpty()) 
	{
		T Temp = GetTop();
		if (Temp <= item)
		{
			Push(item);
		}
		else if (Temp > item)
		{
			while (Temp > item && !IsEmpty())
			{
				s1.Push(Temp);
				Pop();
				if (!IsEmpty())
				{
					Temp = GetTop();
				}
			}
			Push(item);
			while (!s1.IsEmpty())
			{
				Temp = s1.GetTop();
				Push(Temp);
				s1.Pop();
			}
		}
	}
}

template<typename T>
T SeqStack<T>::Pop()
{
	if (IsEmpty())
	{
		cout << "There is no element!" << endl;
		exit(1);
	}
	return Element[Top--];
}

template<typename T>
T SeqStack<T>::GetTop() const
{
	if (IsEmpty())
	{
		cout << "There is no element!" << endl;
		exit(1);
	}
	return Element[Top];
}

template<typename T>
void SeqStack<T>::Print()
{
	cout << "bottom";
	for (int i = 0; i <= Top; i++)
	{
		cout << "->" << Element[i];
	}
	cout << "->top" << endl;
}
int main()
{
	int Arr[]={1,2,6,9,0,3,8,7,5,4,20};
	int Len = sizeof(Arr) / sizeof(Arr[0]);
	SeqStack<int> stack(Len);
	for(int i=0;i<Len;i++)
	{
		stack.MaxStackPush(Arr[i],Len);
	}
	for (int i = 0; i<Len; i++)
	{
		cout<<stack.Pop()<<" ";
	}
	cout << endl;
	stack.Print();
}

執行結果: