Tuesday, April 7, 2015

[Code Interview Problem] Building a SuperStack

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


3 comments:

  1. static void superStack(String[] operations) {
    if (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());

    }

    }

    ReplyDelete
    Replies
    1. listIterator.set(listIterator.next() + k);

      Delete
  2. The Best Bet of 2021: The Best Bookies for Slots in Ghana
    What 강원 랜드 여자 앵벌이 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.

    ReplyDelete