You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This gist contains some useful data structure and algorithm implementations. Note that some of these are not optimized enough for real use cases. The purpose of these snippets are to demonstrate the algorithm.
There are better guides and tutorials out there: w3schools, tutorialspoint, geeksforgeeks. Please refer to them for better knowledge. This is just an all in one place cheatsheet.
Stack<Integer> stack = newStack<Integer>(10);
// push elements to the stackstack.push(1);
stack.push(2);
stack.push(3);
// peek the top most elementSystem.out.println(stack.peek()); // 3// pop elements from the stackSystem.out.println(stack.pop()); // 3System.out.println(stack.pop()); // 2System.out.println(stack.pop()); // 1
Classic string reverse problem
Stringstr = "seniru";
Stack<Character> stack = newStack<Character>(str.length());
// add characters to the aarray one by onefor (Characterc : str.toCharArray()) {
stack.push(c);
}
// reverse the stringwhile (!stack.isEmpty()) {
System.out.print(stack.pop()); // urines
}
System.out.println();
Queue
Access
Search
Insertion
Deletion
Best case
O(1)
O(n)
O(1)
O(1)
Worst case
O(1)
O(n)
O(1)
O(1)
Queue<Integer> queue = newQueue<Integer>(10);
// insert items to the queuequeue.insert(1);
queue.insert(2);
queue.insert(3);
// peek the front of the queueSystem.out.println(queue.peek()); // 1// remove items from the queueSystem.out.println(queue.remove()); // 1System.out.println(queue.remove()); // 2System.out.println(queue.remove()); // 3