Build a Super Stack.
-------------------------------------------------------------------------
Requirements:
- Print value of "peak" after each operation.
- n : the number of operations
- POP : get the value of "peak", if there is no more value after pop, then print "EMPTY"
- PUSH d : put the new value(d) after "peak", then print the value of "peak"
- INC x d : add the new value(d) from index 0 to x elements, then print the value of "peak"
- Example
input :
8
PUSH 1
POP
PUSH 3
PUSH 4
PUSH 5
INC 3 1
POP
PUSH 9
output :
1
EMPTY
3
4
5
6
4
9
the values in the Super Stack
peak 9
5
base 4
-----------------------------------------------------------------------------------------------------------
Show Source code
import java.util.StringTokenizer;
public class SuperStack {
public static void main(String[] argv) {
String[] cmds = {"14", "PUSH 4", "POP", "PUSH 3", "PUSH 5", "PUSH 2"
, "INC 3 1", "POP", "PUSH 1", "INC 2 2", "PUSH 4"
, "POP", "POP", "PUSH 10", "PUSH 11"};
String cmd = null;
int[] stk = new int[100];
int here = -1;
int n = Integer.parseInt( cmds[0] );
for( int i=1; i<=n; i++ ) {
StringTokenizer st = new StringTokenizer( cmds[i], " " );
cmd = st.nextToken();
if( "POP".compareTo(cmd) == 0 ) {
if( here == 0 ) {
here--;
// Do POP
System.out.println("EMPTY");
}
else {
here--;
// Do POP
System.out.println(stk[here]);
}
} else if( "PUSH".compareTo(cmd) == 0 ) {
stk[++here] = Integer.parseInt(st.nextToken());
// Do PUSH
System.out.println(stk[here]);
} else if( "INC".compareTo(cmd) == 0 ) {
int t = Integer.parseInt(st.nextToken());
int d = Integer.parseInt(st.nextToken());
for( int k=0; k<t; k++ ) {
stk[k] = stk[k] + d;
}
System.out.println(stk[here]);
}
}
System.out.println("-Top---------------------------");
for( int i=here; i>=0; i-- ) {
System.out.println(stk[i]);
}
System.out.println("-Bottom------------------------");
}
}
static void superStack(String[] operations) {
ReplyDeleteif (operations == null || operations.length == 0) {
System.out.println("EMPTY");
return;
}
LinkedList list = new LinkedList<>();
for (int i = 0; i < operations.length; i++) {
String current = operations[i];
if (current.equals("pop")) {
list.removeLast();
} else {
if (current.startsWith("push")) {
list.addLast(Integer.parseInt(current.split(" ")[1]));
} else {
int e = Integer.parseInt(current.split(" ")[1]);
int k = Integer.parseInt(current.split(" ")[2]);
ListIterator listIterator = list.listIterator();
int j = 1;
while (listIterator.hasNext()) {
if (j > e)
break;
listIterator.set(listIterator.next() + k);
j++;
}
}
}
if (list.isEmpty())
System.out.println("EMPTY");
else
System.out.println(list.getLast());
}
}
listIterator.set(listIterator.next() + k);
DeleteThe Best Bet of 2021: The Best Bookies for Slots in Ghana
ReplyDeleteWhat 강원 랜드 여자 앵벌이 does the best 하랑 도메인 Bet of 2021 bet mean in the best betting 파워 볼 검증 사이트 markets? betting has become 윈벳 an increasingly popular form of entertainment for fans 야구 사이트 around the world.