码迷,mamicode.com
首页 > 其他好文 > 详细

CC150 3.6

时间:2014-11-27 08:02:46      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:interview

3.6 Write a program to sort a stack in ascending order. You should not make any assumptions about how the stack is implemented. The following are the only functions that should be used to write this program: push | pop | peek | isEmpty.

interface Stack<T>
{
  push(T t);
  T pop();
  T peek();
  boolean isEmpty();
}

// Sort a stack?
// Does it mean changing the order of elements in the stack?
// What about popping all elements out to a list, sorting, and pushing back?

sort(Stack<T> stack)
{

  Stack<T> temp = initStack();
  Stack<T> toReturn = initStack();
  
  while (!stack.isEmpty())
  {
    T t = stack.pop();
    while (!toReturn.isEmpty() && t > toReturn.peek())
    {
      temp.push(toReturn.pop());
    }
    toReturn.push(t);
    while (!temp.isEmpty())
    {
      toReturn.push(temp.pop());
    }
  }
  
  return toReturn;
}


CC150 3.6

标签:interview

原文地址:http://7371901.blog.51cto.com/7361901/1583037

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!