CTCI 3.3

Imagine a (literal) stack of plates. If the stack gets too high, it might topple. Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold. Implement a data structureSetOf Stacks that mimics this. SetOf Stacks should be composed of several stacks and should create a new stack once the previous one exceeds capacity. SetOfStacks.push() and SetOfStacks.pop() should be have identically to a single stack(that is,pop() should return the same values as it would if there were just a single stack).
FOLLOW UP
Implement a function popAt(int index) which performs a pop operation on a specific sub-stack.

Using arraylist could easily implement stacks, and use another arraylist to manage these stacks, when the current stack is full, add a new one, when the current is empty, remove it from the list. In terms of popAt(), I assume that after pop the top from the specific stack, the hole would not be filled in the following push process. We could ask interviewer to clarify this problem. Besides, I assume the data type to be integer, we could use generalization to implement the class.

/*Use arraylist to implement stacks and another arraylist to store these stacks, assume the elements
are integer to ease the discussion. I assume that after a popAt() call, the newly pushed elements should
still see the entire stack as a single stack.*/

import java.util.*;

public class SetofStacks {
    ArrayList<ArrayList<Integer>> sets;
    int stackSize; int stackNum = -1;
    public SetofStacks(int size) {
        sets = new ArrayList<ArrayList<Integer>>();
        stackSize = size;
    } 

    public void push(int key) {
        //If there is no stack yet or the current stack is full, create a new one
        if(stackNum == -1 || sets.get(stackNum).size()+1 > stackSize) {
            sets.add(new ArrayList<Integer>());
            stackNum++;
        }
        sets.get(stackNum).add(key);
    }

    public int pop() throws Exception {
        if(stackNum == -1) {
            throw new Exception("No Elements");
        }

        int top = sets.get(stackNum).size();
        int key = sets.get(stackNum).get(top-1);
        sets.get(stackNum).remove(top-1);

        //If a stack is empty, remove it from the list
        if(sets.get(stackNum).size() == 0) {
            sets.remove(stackNum);
            stackNum--;
        }

        return key;
    }

    public int popAt(int index) throws Exception{
        if(stackNum < index) {
            throw new Exception("No Such Stack");
        }

        int top = sets.get(index).size();
        int key = sets.get(index).get(top-1);
        sets.get(index).remove(top-1);

        return key;
    }

    public static void main(String[] args) {
        SetofStacks ss = new SetofStacks(2);
        try {
            ss.push(1); ss.push(2); ss.push(3);
            System.out.println(ss.pop() + " " + ss.pop() + " " +ss.pop());
            ss.push(1); ss.push(2); ss.push(3); ss.push(4);
            System.out.println(ss.popAt(0) + " " + ss.popAt(1));
            ss.push(5); ss.push(6);
            System.out.println(ss.pop() + " " + ss.pop() + " " +ss.pop());
        }
        catch(Exception e) {
            System.out.println(e.toString());
        }
    }
}

CTCI 3.3

时间: 2024-10-23 22:24:35

CTCI 3.3的相关文章

CTCI 3.4

In the classic problem of the Towers of Hanoi, you have 3 towers and Ndisks of different sizes which can slide onto any tower.The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even la

CTCI 2.3

Implement an algorithm to delete a node in the middle of a singly linked list, given only access to that node.EXAMPLEInput: the node c from the linked list a->b->c->d->eResult: nothing isreturned, but the new linked list looks like a- >b- &

CTCI 1.3

Description: Given two strings, write a method to decide if one is a permutation of the other. We could use the same idea from CTCI 1.1. The only difference is that in 1.1 we just need to know whether one character appear or not, in this problem we n

CTCI 2.1

Write code to remove duplicates from an unsorted linked list.FOLLOW UPHow would you solve this problem if a temporary buffer is not allowed? /* Use a HashSet to record whether a val has appeared or not. We assume that the linked list is singly linked

CTCI 2.2

Implement an algorithm to find the kth to last element of a singly linked list. Classical "Runner" Technique of linkedlist /*Use two pointers, forward one K nodes, then the two pointers form a "window" contains K nodes. Then move two p

CTCI 3.1

Describe how you could use a single array to implement three stacks. Divide the array into three fixed parts, each stands for a stack. /*Fixed Size Stacks*/ import java.util.*; public class ThreeStacks { int stackSize = 100; int[] buffer = new int[st

CTCI 2.7

Implement a function to check if a linked list is a palindrome. Reverse the second half of the list and then compare it with the first half. /* Assume that we can destroy the list, reverse the second half of the list and compare it with the first hal

CTCI 1.2

Since I mainly use Java, this problem seems meaning less for me to implement it with Java. Just use StringBuilder to append each character in string from the end to the start. The time complexity is O(N) and space complexity is O(N), too. If using C+

CTCI 4.8

You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1. A tree T2 is a subtree of T1 if there exist a node in T1 such that the subtree of nis identical