我有一个Stack变量(java集合),它包含五个整数,我也得到了一个int变量。是否可以对给定堆栈中的数字进行排序。我无法解决这个问题。如果您有任何想法,请在此发布。
Stack<Integer> s = new Stack<Integer>();
s.push(5);s.push(3);s.push(4);s.push(1);s.push(1);
int a;
除上述代码段中给出的变量外,我们不应创建任何新变量,也不应使用Collections.sort(s)。
答案 0 :(得分:2)
非常低效,但尊重规则:)
Stack<Integer> s=new Stack<Integer>();
s.push(5);s.push(3);s.push(4);s.push(1);s.push(1);
int a = -1;
while (a == -1) { // Here 'a' is used as a kind of boolean that tells us whether we need to keep checking for items to reorder or not.
for (a = 0; a < s.size() - 1; a++) { // Now 'a' becomes stack element's index.
if (s.get(a) > s.get(a + 1)) {
a = s.remove(a); // Here 'a' again changes meaning and holds the value that needs to be reordered.
s.push(a);
a = -1; // And here, 'a' is back to being used as a kind of boolean flag to control the outer loop.
break;
}
}
}
修改强>:
基本上,我利用了这个事实,即我知道Stack
延伸Vector
。因此,我实际上不必仅使用标准的Pop
和Push
方法来访问/删除元素。我可以使用普通的List
方法。
然后,我只是在a
中通过在不同时间将它用于不同目的(挤出标志,循环索引,临时存储以便重新排序的值)来尽可能地挤出a
。通常是一个非常糟糕的编程习惯。
所以算法基本上就是我遍历Stack元素。每当我发现一个大于下一个元素的元素时,我将其删除,然后将其放在堆栈的末尾。在那一刻,我停止循环,并将-1
重置为Stack
以确保我再次启动循环。我一直这样做,直到我能够遍历所有堆栈项而不需要重新排序任何东西。
编辑2 :
这是另一种选择,它有点复杂,但仍然遵守规则,并且在冒泡排序模式后表现更好。使用的原则与我的第一次尝试几乎相同(将List
滥用为a
+使用变量Stack<Integer> s=new Stack<Integer>();
s.push(5);s.push(3);s.push(4);s.push(1);s.push(1);
int a = -1;
while (a < 0) { // keep looping if the previous loop performed at least one swap.
a = 0;
// if 'a' is >= 0, then it simply holds the index.
// if 'a' < 0, then the index can be obtained by applying the bitwise complement operator.
while ((a < 0 ? ~a : a) < (s.size() - 1)) { // loop all items except the last one.
if (s.get(a < 0 ? ~a : a) > s.get((a < 0 ? ~a : a) + 1)) { // if this item is greater than the next, a swap is needed.
s.insertElementAt(s.remove(a < 0 ? ~a : a), (a < 0 ? ~a : a) + 1); // swap this value with the next.
// If this was not done already, flag the fact that a swap was performed by
// applying the bitwise complement operator to 'a'.
// This serves as a flag to let the outer loop know
// that we'll need to perform the stack loop again.
if (a >= 0) {
a = ~a;
}
}
// increment index. Or if the bitwise complement operator was applied,
// then go the opposite way since the value is now negative.
if (a >= 0) {
a++;
} else {
a--;
}
}
}
进行多次使用)。
Math.abs()
编辑3:修改了我的上一个算法,使用了按位补码运算符,而不是StackOverflowException
。
另外,我想指出的是,与其他一些聪明的尝试不同,这种算法并没有任何限制。由于递归调用太多,它不会受int
的影响,因为没有使用递归。使用的内存是稳定的。您可以在Stack
中获得任何//factory
.factory("uploadFactory", function ($http) {
return {
// upload: $resource("/api/EasyPay/")
upload: function (data) {
$http({
method: 'POST',
url: "/api/Upload",
headers: { 'Content-Type': undefined },
//some transformations....
data: { model: data.model, files: data.files }
}).
success(function (data, status, headers, config) {
alert("success!");
}).
error(function (data, status, headers, config) {
alert("failed!");
});
}
};
});
//controller
.controller("SeguiAttivazioneController", function ($scope, SeguiAttivazioneService, uploadFactory) {
...
//an array of files selected
$scope.files = [];
//listen for the file selected event
$scope.$on("fileSelected", function (event, args) {
$scope.$apply(function () {
//add the file object to the scope's files collection
$scope.files.push(args.file);
});
//call factory with $scope.files as 'data' argument
uploadFactory.upload($scope.files);
});
值,甚至是负值,并且它会正常工作。
答案 1 :(得分:1)
这是可能的,但你会稍微作弊 - 你将会使用第二个筹码来做这件事。
我并不是说你明确宣布另一个堆栈;你将通过这种方法进行递归。
请记住,这种方法有一些局限性;它可以很好地处理顺序数据(也就是说,它可以很好地反转堆栈),但处理更多混乱的数据要困难得多,因为我们将来最多只能看到两个元素(peek和holder)。
这也颠倒了这种方法,并没有以你规定的方式(1到5)对它们进行排序,但从代码中找出正确的条件应该是一件小事。
方法是:
null
和empty
堆栈如果下一个堆栈中的内容小于持有者变量,我们采取行动:
否则,我们放回我们找到的东西并返回堆栈。
public Stack<Integer> sortStack(Stack<Integer> stack) {
// no-op on empty stacks
if(null == stack || stack.empty()) {
return stack;
}
// pop stack and place in holder
while(true) {
int holder = stack.pop();
// no-op on stacks of size 1
try {
stack.peek();
} catch(EmptyStackException e) {
// Stack only had one element; put it back and return the stack
stack.push(holder);
return stack;
}
if(stack.peek() < holder) {
holder += stack.pop() * 10;
stack.push(holder % 10);
stack = sortStack(stack);
stack.push(holder / 10);
} else {
//put it back
stack.push(holder);
break;
}
}
return stack;
}
答案 2 :(得分:0)
由于Stack
实施List
而Integer
实施Comparable
只是:
Collections.sort(s);
答案 3 :(得分:0)
您可以使用冒泡排序来执行此操作,如下所示:
Stack<Integer> s = new Stack();
s.push(5);
s.push(3);
s.push(4);
s.push(1);
s.push(1);
int a = 0;
while (a != s.size() - 1) {
if (a != s.size() - 1) {
if (s.elementAt(a) >= s.elementAt(a + 1)) {
a++;
} else {
s.push(s.remove(a));
a = 0;
}
}
}
System.out.println(s.toString());
答案 4 :(得分:0)
在这里,我找到了geeksforgeeks使用递归的完美答案。 http://www.geeksforgeeks.org/sort-a-stack-using-recursion/ 只需在此处发布相同的算法。
<强>算法:强>
我们可以使用以下算法对堆栈元素进行排序:
sortStack(stack S)
if stack is not empty:
temp = pop(S);
sortStack(S);
sortedInsert(S, temp);
下面的算法是插入元素的排序顺序:
sortedInsert(Stack S, element)
if stack is empty OR element > top element
push(S, elem)
else
temp = pop(S)
sortedInsert(S, element)
push(S, temp)