Last active
May 27, 2017 08:59
-
-
Save anil477/24e111be03586d49452739e41b69b1c3 to your computer and use it in GitHub Desktop.
Sort a stack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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