首页 > 代码库 > CC150 3.6
CC150 3.6
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。