Will keep on sharing Data Structure questions...
Below is one coding question asked around the knowledge of Data Structures.
Stacks, Queues, List, Set & Trees are the items against which you can be grilled by the interviewer along with the algorithms using these Data Structures. Here I will try to put some sample codes & you can also look the section - Coding Interviews
// Sort the stack of numbers using only one more stack
import java.util.Random;
import java.util.Stack;
public class StackSort {
public static void main(String[] args) {
Stack<Integer> stack1 = new Stack<>();
int range = 1000000;
Random random = new Random();
for(int i = 0; i < range; i++) {
stack1.push(random.nextInt(range));
}
long start = System.currentTimeMillis();
sort(stack1);
System.out.println("Time taken :- " + (System.currentTimeMillis()-start) + " ms");
}
public static void sort(Stack<Integer> stack1) {
Stack<Integer> stack2 = new Stack<>();
int next = stack1.pop();
if(stack2.isEmpty()) {
stack2.push(next);
}
while(!stack1.isEmpty() && !stack2.isEmpty()) {
int s1 = stack1.pop();
while(!stack2.isEmpty() && s1 > stack2.peek()) {
stack1.push(stack2.pop());
}
stack2.push(s1);
}
}
}
Stacks, Queues, List, Set & Trees are the items against which you can be grilled by the interviewer along with the algorithms using these Data Structures. Here I will try to put some sample codes & you can also look the section - Coding Interviews
// Sort the stack of numbers using only one more stack
import java.util.Random;
import java.util.Stack;
public class StackSort {
public static void main(String[] args) {
Stack<Integer> stack1 = new Stack<>();
int range = 1000000;
Random random = new Random();
for(int i = 0; i < range; i++) {
stack1.push(random.nextInt(range));
}
long start = System.currentTimeMillis();
sort(stack1);
System.out.println("Time taken :- " + (System.currentTimeMillis()-start) + " ms");
}
public static void sort(Stack<Integer> stack1) {
Stack<Integer> stack2 = new Stack<>();
int next = stack1.pop();
if(stack2.isEmpty()) {
stack2.push(next);
}
while(!stack1.isEmpty() && !stack2.isEmpty()) {
int s1 = stack1.pop();
while(!stack2.isEmpty() && s1 > stack2.peek()) {
stack1.push(stack2.pop());
}
stack2.push(s1);
}
}
}