Skip to content

Instantly share code, notes, and snippets.

@anil477
Last active May 27, 2017 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/24e111be03586d49452739e41b69b1c3 to your computer and use it in GitHub Desktop.
Save anil477/24e111be03586d49452739e41b69b1c3 to your computer and use it in GitHub Desktop.
Sort a stack
import java.util.*;
class sort{
public static void main(String args[]) {
Stack<Integer> s = new Stack<Integer>();
s.push(10);
s.push(8);
s.push(11);
s.push(1);
s.push(3);
System.out.println(" Original Stack Before Sort:" + s.toString());
sort(s);
System.out.println(" Original Stack After Sort:" + s.toString());
}
public static void sort(Stack<Integer> stack)
{
if (stack == null || stack.isEmpty()) {
System.out.println("Empty");
return;
}
Stack<Integer> newStack = new Stack<Integer>();
newStack.push(stack.pop());
while (!stack.isEmpty()) {
int temp = stack.pop();
while (!newStack.isEmpty() && temp > newStack.peek()) {
stack.push(newStack.pop());
}
newStack.push(temp);
}
System.out.println(" New Stack Afetr Sort :" + newStack.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment