The design of a data structure, which conforms to the characteristics of the stack, that is, "LIFO", and add one more requirements, so that all elements of the stack to remove the maximum time complexity can be controlled O (1).
To say a very obvious error, use a secondary variable, save the current maximum value, each time the value of the stack is compared to the maximum value, the larger is replaced with the maximum.
This takes out the maximum value and returns the auxiliary variable, which is clearly only a single correct return.
The overall implementation is very simple, is to open more than one store the maximum index of the stack, the stack and the stack of data stored in sync, that is, the top of the stack pointer at the same time function of the two stacks.
The code is simple too, so it's not explained.
The Java code is as follows:
public class Maxnumfromstack {public static void main (string[] args) {mystack stack=new mystack ();
Stack.push (2);
Stack.push (3);
Stack.push (4);
Stack.push (5);
Stack.push (1);
Stack.push (10);
Stack.push (8);
for (int i=0;i<6;i++) {System.out.println ("Thenum:" +stack.pop ());
System.out.println ("Maxnum:" +stack.getmax ());
System.out.println ("=========================");
Class mystack{private int top;
private int maxindex;
private int MAX;
Private int[] data;
Private int[] Maxstackindex;
Public Mystack () {max=10;
Top=-1;
Maxindex=-1;
Data=new Int[max];
Maxstackindex=new Int[max];
}//into stack public void push (int num) {top++;
if (Top>=max) {System.out.println ("stack is full, cannot enter Stack");
Return
data[top]=num;//is added first to the stack if (Num>getmax ()) {//greater than the current maximum maxstackindex[top]=top;//is currently the maximum maxindex=top;
}else{//Retain the maximum value maxstackindex[top]=maxindex;
}///out Stack public int pop () {if (top<0) {System.out.println ("stack is empty, can't stack"); return integer.min_value;
int Num=data[top];
if (top==0) {maxindex=-1;
}else if (top==maxindex) {//current stack top is maximum, adjust maximum value maxindex=maxstackindex[top-1];
} top--;
return num;
public int Getmax () {if (maxindex>=0) {return data[maxindex];
}else{//Returns the minimum value return integer.min_value; }
}
}
Output:
Thenum:8
maxnum:10
=========================
thenum:10
maxnum:5
=========================
thenum:1
Maxnum:5
=========================
thenum:5
maxnum:4
=========================
thenum:4
maxnum:3
=========================
thenum:3
maxnum:2
=========================