Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 1dcf3a8

Browse filesBrowse files
committed
Added solution for sorted stack
1 parent d584bc1 commit 1dcf3a8
Copy full SHA for 1dcf3a8

File tree

Expand file treeCollapse file tree

2 files changed

+62
-0
lines changed
Open diff view settings
Filter options
Expand file treeCollapse file tree

2 files changed

+62
-0
lines changed
Open diff view settings
Collapse file
+46Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.eprogrammerz.examples.ds.custom.stack;
2+
3+
import java.util.Stack;
4+
5+
public class SortedStack {
6+
7+
private Stack<Integer> stack;
8+
private Stack<Integer> temp;
9+
10+
public SortedStack() {
11+
this.stack = new Stack<>();
12+
this.temp = new Stack<>();
13+
}
14+
15+
public void push(int data) {
16+
if (stack.isEmpty()) {
17+
stack.push(data);
18+
return;
19+
}
20+
int top = stack.peek();
21+
if (data > top) {
22+
// copy samller to temp
23+
while (!stack.isEmpty() && stack.peek() < data) {
24+
temp.push(stack.pop());
25+
}
26+
27+
// push
28+
stack.push(data);
29+
30+
// copy from temp to stack
31+
while (!temp.isEmpty() && temp.peek() != null) {
32+
stack.push(temp.pop());
33+
}
34+
} else {
35+
stack.push(data);
36+
}
37+
}
38+
39+
public int pop() {
40+
return stack.pop();
41+
}
42+
43+
public int peek() {
44+
return stack.peek();
45+
}
46+
}
Collapse file

‎src/main/java/com/eprogrammerz/examples/ds/custom/stack/Validator.java‎

Copy file name to clipboardExpand all lines: src/main/java/com/eprogrammerz/examples/ds/custom/stack/Validator.java
+16Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,4 +54,20 @@ public void testMinStack() {
5454
assertEquals(1, minStack.pop());
5555
assertEquals(2, minStack.min());
5656
}
57+
58+
@Test
59+
public void testSortedStack() {
60+
SortedStack sortedStack = new SortedStack();
61+
sortedStack.push(2);
62+
sortedStack.push(4);
63+
sortedStack.push(1);
64+
sortedStack.push(5);
65+
sortedStack.push(0);
66+
67+
assertEquals(0, sortedStack.pop());
68+
assertEquals(1, sortedStack.pop());
69+
assertEquals(2, sortedStack.pop());
70+
assertEquals(4, sortedStack.pop());
71+
assertEquals(5, sortedStack.pop());
72+
}
5773
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.