[Algo] 280. Sort With 2 Stacks

Given an array that is initially stored in one stack, sort it with one additional stacks (total 2 stacks).

After sorting the original stack should contain the sorted integers and from top to bottom the integers are sorted in ascending order.

Assumptions:

  • The given stack is not null.
  • There can be duplicated numbers in the give stack.

Requirements:

  • No additional memory, time complexity = O(n ^ 2).
public class Solution {
  public void sort(LinkedList<Integer> s1) {
    LinkedList<Integer> s2 = new LinkedList<Integer>();
    // Write your solution here.
    while (!s1.isEmpty()) {
      s2.offerFirst(s1.pollFirst());
    }

    while (!s2.isEmpty()) {
      Integer cur = s2.pollFirst();
      while (!s1.isEmpty() && cur > s1.peekFirst()) {
        s2.offerFirst(s1.pollFirst());
      }
      s1.offerFirst(cur);
    }
  }
}

 

posted @ 2020-02-19 11:05  xuan_abc  阅读(164)  评论(0编辑  收藏  举报