Implementing Patience Sort with LinkedList

时间:2015-07-28 16:07:24

标签: java sorting linked-list stack

According to my notes, the patience sort divides data into a number of bins, and then combines the contents of those bins into a complete list.

I think I get the general idea of how to do this, but one of the requirements is to have a LinkedList for the list of ints, the list of stacks, and the stack itself.

So what confuses me, is how I'm suppose to add each stack to the LinkedList, when the LinkedList accepts ints, not stacks. I could change the LinkedList to accept stacks, but then when I originally created the list to be sorted in the main method, it was done with ints.

I know I'm missing something obvious, but I can't see how this can be done, any suggestions? I've included my sort method below, with some commented out code of how things could be done (but I'm not sure if it is right).

public void sort() {
    LinkedList listOfStacks = new LinkedList();
    //LinkedList<Stacks> listOfStacks = new LinkedList()<Stacks>;
    int [] listOfInts =  {8, 5, 3, 4, 1, 2, 6, 9, 7};

    for(int i = 0; i < listOfInts.length; i++) {
        LinkedList stack = new LinkedList();
        // No stacks initially, create first stack,
        // and add first element
        if(listOfStacks.getSize() == 0) {
            // listOfStacks.add(stack);
        }

        for(int j = 0; j < listOfStacks.getSize(); j++) {
            if(stack.getSize() == 0) {
                stack.push(listOfInts[i]);
                // listOfStacks.add(stack);
            }
            else if(stack.peek() < listOfInts[i]) {
                stack.push(listOfInts[i]);
                // listOfStacks.add(stack);
                break;
            }
            else {
                LinkedList newStack = new LinkedList();
                newStack.push(listOfInts[i]);
                // listOfStacks.add(newStack);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

Rather than trying to add the stack to the linked list directly, pop values off the stack into the linked list until the stack is empty.

Alternatively, if you may declare your linked list of stacks to accept other linked lists, rather than ints:

LinkedList<LinkedList<Integer>> listOfStacks = new LinkedList<LinkedList<Integer>>();