mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-27 06:23:08 +08:00
Change project structure to a Maven Java project + Refactor (#2816)
This commit is contained in:

committed by
GitHub

parent
8e533d2617
commit
9fb3364ccc
@ -0,0 +1,82 @@
|
||||
package com.thealgorithms.datastructures.stacks;
|
||||
|
||||
import java.util.Stack;
|
||||
|
||||
/**
|
||||
* The nested brackets problem is a problem that determines if a sequence of
|
||||
* brackets are properly nested. A sequence of brackets s is considered properly
|
||||
* nested if any of the following conditions are true: - s is empty - s has the
|
||||
* form (U) or [U] or {U} where U is a properly nested string - s has the form
|
||||
* VW where V and W are properly nested strings For example, the string
|
||||
* "()()[()]" is properly nested but "[(()]" is not. The function called
|
||||
* is_balanced takes as input a string S which is a sequence of brackets and
|
||||
* returns true if S is nested and false otherwise.
|
||||
*
|
||||
* @author akshay sharma
|
||||
* @author <a href="https://github.com/khalil2535">khalil2535<a>
|
||||
* @author shellhub
|
||||
*/
|
||||
class BalancedBrackets {
|
||||
|
||||
/**
|
||||
* Check if {@code leftBracket} and {@code rightBracket} is paired or not
|
||||
*
|
||||
* @param leftBracket left bracket
|
||||
* @param rightBracket right bracket
|
||||
* @return {@code true} if {@code leftBracket} and {@code rightBracket} is
|
||||
* paired, otherwise {@code false}
|
||||
*/
|
||||
public static boolean isPaired(char leftBracket, char rightBracket) {
|
||||
char[][] pairedBrackets = {
|
||||
{'(', ')'},
|
||||
{'[', ']'},
|
||||
{'{', '}'},
|
||||
{'<', '>'}
|
||||
};
|
||||
for (char[] pairedBracket : pairedBrackets) {
|
||||
if (pairedBracket[0] == leftBracket && pairedBracket[1] == rightBracket) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if {@code brackets} is balanced
|
||||
*
|
||||
* @param brackets the brackets
|
||||
* @return {@code true} if {@code brackets} is balanced, otherwise
|
||||
* {@code false}
|
||||
*/
|
||||
public static boolean isBalanced(String brackets) {
|
||||
if (brackets == null) {
|
||||
throw new IllegalArgumentException("brackets is null");
|
||||
}
|
||||
Stack<Character> bracketsStack = new Stack<>();
|
||||
for (char bracket : brackets.toCharArray()) {
|
||||
switch (bracket) {
|
||||
case '(':
|
||||
case '[':
|
||||
case '{':
|
||||
bracketsStack.push(bracket);
|
||||
break;
|
||||
case ')':
|
||||
case ']':
|
||||
case '}':
|
||||
if (bracketsStack.isEmpty() || !isPaired(bracketsStack.pop(), bracket)) {
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
/* other character is invalid */
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return bracketsStack.isEmpty();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
assert isBalanced("[()]{}{[()()]()}");
|
||||
assert !isBalanced("[(])");
|
||||
}
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
package com.thealgorithms.datastructures.stacks;
|
||||
|
||||
import java.util.Stack;
|
||||
|
||||
public class DecimalToAnyUsingStack {
|
||||
|
||||
public static void main(String[] args) {
|
||||
assert convert(0, 2).equals("0");
|
||||
assert convert(30, 2).equals("11110");
|
||||
assert convert(30, 8).equals("36");
|
||||
assert convert(30, 10).equals("30");
|
||||
assert convert(30, 16).equals("1E");
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert decimal number to another radix
|
||||
*
|
||||
* @param number the number to be converted
|
||||
* @param radix the radix
|
||||
* @return another radix
|
||||
* @throws ArithmeticException if <tt>number</tt> or <tt>radius</tt> is
|
||||
* invalid
|
||||
*/
|
||||
private static String convert(int number, int radix) {
|
||||
if (radix < 2 || radix > 16) {
|
||||
throw new ArithmeticException(
|
||||
String.format("Invalid input -> number:%d,radius:%d", number, radix));
|
||||
}
|
||||
char[] tables = {
|
||||
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
|
||||
};
|
||||
Stack<Character> bits = new Stack<>();
|
||||
do {
|
||||
bits.push(tables[number % radix]);
|
||||
number = number / radix;
|
||||
} while (number != 0);
|
||||
|
||||
StringBuilder result = new StringBuilder();
|
||||
while (!bits.isEmpty()) {
|
||||
result.append(bits.pop());
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
package com.thealgorithms.datastructures.stacks;
|
||||
|
||||
// 1. You are given a string exp representing an expression.
|
||||
// 2. Assume that the expression is balanced i.e. the opening and closing brackets match with each other.
|
||||
// 3. But, some of the pair of brackets maybe extra/needless.
|
||||
// 4. You are required to print true if you detect extra brackets and false otherwise.
|
||||
// e.g.'
|
||||
// ((a + b) + (c + d)) -> false
|
||||
// (a + b) + ((c + d)) -> true
|
||||
import java.util.*;
|
||||
|
||||
public class DuplicateBrackets {
|
||||
|
||||
public static boolean check(String str) {
|
||||
Stack<Character> st = new Stack<>();
|
||||
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
char ch = str.charAt(i);
|
||||
if (ch == ')') {
|
||||
if (st.peek() == '(') {
|
||||
return true;
|
||||
} else {
|
||||
while (st.size() > 0 && st.peek() != '(') {
|
||||
st.pop();
|
||||
}
|
||||
st.pop();
|
||||
}
|
||||
|
||||
} else {
|
||||
st.push(ch);
|
||||
}
|
||||
// System.out.println(st);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
String str = sc.nextLine();
|
||||
System.out.println(check(str));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
package com.thealgorithms.datastructures.stacks;
|
||||
|
||||
import java.util.Stack;
|
||||
|
||||
public class InfixToPostfix {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
assert "32+".equals(infix2PostFix("3+2"));
|
||||
assert "123++".equals(infix2PostFix("1+(2+3)"));
|
||||
assert "34+5*6-".equals(infix2PostFix("(3+4)*5-6"));
|
||||
}
|
||||
|
||||
public static String infix2PostFix(String infixExpression) throws Exception {
|
||||
if (!BalancedBrackets.isBalanced(infixExpression)) {
|
||||
throw new Exception("invalid expression");
|
||||
}
|
||||
StringBuilder output = new StringBuilder();
|
||||
Stack<Character> stack = new Stack<>();
|
||||
for (char element : infixExpression.toCharArray()) {
|
||||
if (Character.isLetterOrDigit(element)) {
|
||||
output.append(element);
|
||||
} else if (element == '(') {
|
||||
stack.push(element);
|
||||
} else if (element == ')') {
|
||||
while (!stack.isEmpty() && stack.peek() != '(') {
|
||||
output.append(stack.pop());
|
||||
}
|
||||
stack.pop();
|
||||
} else {
|
||||
while (!stack.isEmpty() && precedence(element) <= precedence(stack.peek())) {
|
||||
output.append(stack.pop());
|
||||
}
|
||||
stack.push(element);
|
||||
}
|
||||
}
|
||||
while (!stack.isEmpty()) {
|
||||
output.append(stack.pop());
|
||||
}
|
||||
return output.toString();
|
||||
}
|
||||
|
||||
private static int precedence(char operator) {
|
||||
switch (operator) {
|
||||
case '+':
|
||||
case '-':
|
||||
return 0;
|
||||
case '*':
|
||||
case '/':
|
||||
return 1;
|
||||
case '^':
|
||||
return 2;
|
||||
default:
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,106 @@
|
||||
package com.thealgorithms.datastructures.stacks;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Stack;
|
||||
|
||||
/**
|
||||
* Given an integer array. The task is to find the maximum of the minimum of
|
||||
* every window size in the array. Note: Window size varies from 1 to the size
|
||||
* of the Array.
|
||||
* <p>
|
||||
* For example,
|
||||
* <p>
|
||||
* N = 7
|
||||
* arr[] = {10,20,30,50,10,70,30}
|
||||
* <p>
|
||||
* So the answer for the above would be : 70 30 20 10 10 10 10
|
||||
* <p>
|
||||
* We need to consider window sizes from 1 to length of array in each iteration.
|
||||
* So in the iteration 1 the windows would be [10], [20], [30], [50], [10],
|
||||
* [70], [30]. Now we need to check the minimum value in each window. Since the
|
||||
* window size is 1 here the minimum element would be the number itself. Now the
|
||||
* maximum out of these is the result in iteration 1. In the second iteration we
|
||||
* need to consider window size 2, so there would be [10,20], [20,30], [30,50],
|
||||
* [50,10], [10,70], [70,30]. Now the minimum of each window size would be
|
||||
* [10,20,30,10,10] and the maximum out of these is 30. Similarly we solve for
|
||||
* other window sizes.
|
||||
*
|
||||
* @author sahil
|
||||
*/
|
||||
public class MaximumMinimumWindow {
|
||||
|
||||
/**
|
||||
* This function contains the logic of finding maximum of minimum for every
|
||||
* window size using Stack Data Structure.
|
||||
*
|
||||
* @param arr Array containing the numbers
|
||||
* @param n Length of the array
|
||||
* @return result array
|
||||
*/
|
||||
public static int[] calculateMaxOfMin(int[] arr, int n) {
|
||||
Stack<Integer> s = new Stack<>();
|
||||
int left[] = new int[n + 1];
|
||||
int right[] = new int[n + 1];
|
||||
for (int i = 0; i < n; i++) {
|
||||
left[i] = -1;
|
||||
right[i] = n;
|
||||
}
|
||||
|
||||
for (int i = 0; i < n; i++) {
|
||||
while (!s.empty() && arr[s.peek()] >= arr[i]) {
|
||||
s.pop();
|
||||
}
|
||||
|
||||
if (!s.empty()) {
|
||||
left[i] = s.peek();
|
||||
}
|
||||
|
||||
s.push(i);
|
||||
}
|
||||
|
||||
while (!s.empty()) {
|
||||
s.pop();
|
||||
}
|
||||
|
||||
for (int i = n - 1; i >= 0; i--) {
|
||||
while (!s.empty() && arr[s.peek()] >= arr[i]) {
|
||||
s.pop();
|
||||
}
|
||||
|
||||
if (!s.empty()) {
|
||||
right[i] = s.peek();
|
||||
}
|
||||
|
||||
s.push(i);
|
||||
}
|
||||
|
||||
int ans[] = new int[n + 1];
|
||||
for (int i = 0; i <= n; i++) {
|
||||
ans[i] = 0;
|
||||
}
|
||||
|
||||
for (int i = 0; i < n; i++) {
|
||||
int len = right[i] - left[i] - 1;
|
||||
|
||||
ans[len] = Math.max(ans[len], arr[i]);
|
||||
}
|
||||
|
||||
for (int i = n - 1; i >= 1; i--) {
|
||||
ans[i] = Math.max(ans[i], ans[i + 1]);
|
||||
}
|
||||
|
||||
// Print the result
|
||||
for (int i = 1; i <= n; i++) {
|
||||
System.out.print(ans[i] + " ");
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
|
||||
public static void main(String args[]) {
|
||||
int[] arr = new int[]{10, 20, 30, 50, 10, 70, 30};
|
||||
int[] target = new int[]{70, 30, 20, 10, 10, 10, 10};
|
||||
int[] res = calculateMaxOfMin(arr, arr.length);
|
||||
assert Arrays.equals(target, res);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,180 @@
|
||||
package com.thealgorithms.datastructures.stacks;
|
||||
|
||||
/**
|
||||
* Implementation of a stack using nodes. Unlimited size, no arraylist.
|
||||
*
|
||||
* @author Kyler Smith, 2017
|
||||
*/
|
||||
public class NodeStack<Item> {
|
||||
|
||||
/**
|
||||
* Entry point for the program.
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
NodeStack<Integer> Stack = new NodeStack<Integer>();
|
||||
|
||||
Stack.push(3);
|
||||
Stack.push(4);
|
||||
Stack.push(5);
|
||||
System.out.println("Testing :");
|
||||
Stack.print(); // prints : 5 4 3
|
||||
|
||||
Integer x = Stack.pop(); // x = 5
|
||||
Stack.push(1);
|
||||
Stack.push(8);
|
||||
Integer y = Stack.peek(); // y = 8
|
||||
System.out.println("Testing :");
|
||||
Stack.print(); // prints : 8 1 4 3
|
||||
|
||||
System.out.println("Testing :");
|
||||
System.out.println("x : " + x);
|
||||
System.out.println("y : " + y);
|
||||
}
|
||||
|
||||
/**
|
||||
* Information each node should contain.
|
||||
*
|
||||
* @value data : information of the value in the node
|
||||
* @value head : the head of the stack
|
||||
* @value next : the next value from this node
|
||||
* @value previous : the last value from this node
|
||||
* @value size : size of the stack
|
||||
*/
|
||||
private Item data;
|
||||
|
||||
private static NodeStack<?> head;
|
||||
private NodeStack<?> next;
|
||||
private NodeStack<?> previous;
|
||||
private static int size = 0;
|
||||
|
||||
/**
|
||||
* Constructors for the NodeStack.
|
||||
*/
|
||||
public NodeStack() {
|
||||
}
|
||||
|
||||
private NodeStack(Item item) {
|
||||
this.data = item;
|
||||
}
|
||||
|
||||
/**
|
||||
* Put a value onto the stack.
|
||||
*
|
||||
* @param item : value to be put on the stack.
|
||||
*/
|
||||
public void push(Item item) {
|
||||
|
||||
NodeStack<Item> newNs = new NodeStack<Item>(item);
|
||||
|
||||
if (this.isEmpty()) {
|
||||
NodeStack.setHead(new NodeStack<>(item));
|
||||
newNs.setNext(null);
|
||||
newNs.setPrevious(null);
|
||||
} else {
|
||||
newNs.setPrevious(NodeStack.head);
|
||||
NodeStack.head.setNext(newNs);
|
||||
NodeStack.head.setHead(newNs);
|
||||
}
|
||||
|
||||
NodeStack.setSize(NodeStack.getSize() + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Value to be taken off the stack.
|
||||
*
|
||||
* @return item : value that is returned.
|
||||
*/
|
||||
public Item pop() {
|
||||
|
||||
Item item = (Item) NodeStack.head.getData();
|
||||
|
||||
NodeStack.head.setHead(NodeStack.head.getPrevious());
|
||||
NodeStack.head.setNext(null);
|
||||
|
||||
NodeStack.setSize(NodeStack.getSize() - 1);
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
/**
|
||||
* Value that is next to be taken off the stack.
|
||||
*
|
||||
* @return item : the next value that would be popped off the stack.
|
||||
*/
|
||||
public Item peek() {
|
||||
return (Item) NodeStack.head.getData();
|
||||
}
|
||||
|
||||
/**
|
||||
* If the stack is empty or there is a value in.
|
||||
*
|
||||
* @return boolean : whether or not the stack has anything in it.
|
||||
*/
|
||||
public boolean isEmpty() {
|
||||
return NodeStack.getSize() == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the size of the stack.
|
||||
*
|
||||
* @return int : number of values in the stack.
|
||||
*/
|
||||
public int size() {
|
||||
return NodeStack.getSize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Print the contents of the stack in the following format.
|
||||
*
|
||||
* <p>
|
||||
* x <- head (next out) y z <- tail (first in) . . .
|
||||
*/
|
||||
public void print() {
|
||||
for (NodeStack<?> n = NodeStack.head; n != null; n = n.previous) {
|
||||
System.out.println(n.getData().toString());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Getters and setters (private)
|
||||
*/
|
||||
private NodeStack<?> getHead() {
|
||||
return NodeStack.head;
|
||||
}
|
||||
|
||||
private static void setHead(NodeStack<?> ns) {
|
||||
NodeStack.head = ns;
|
||||
}
|
||||
|
||||
private NodeStack<?> getNext() {
|
||||
return next;
|
||||
}
|
||||
|
||||
private void setNext(NodeStack<?> next) {
|
||||
this.next = next;
|
||||
}
|
||||
|
||||
private NodeStack<?> getPrevious() {
|
||||
return previous;
|
||||
}
|
||||
|
||||
private void setPrevious(NodeStack<?> previous) {
|
||||
this.previous = previous;
|
||||
}
|
||||
|
||||
private static int getSize() {
|
||||
return size;
|
||||
}
|
||||
|
||||
private static void setSize(int size) {
|
||||
NodeStack.size = size;
|
||||
}
|
||||
|
||||
private Item getData() {
|
||||
return this.data;
|
||||
}
|
||||
|
||||
private void setData(Item item) {
|
||||
this.data = item;
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
# STACK
|
||||
|
||||
Stack is an ADT (abstract data type) that acts like a list of objects but there is a difference.
|
||||
|
||||
Stack works on the principle of _LIFO_ (Last In First Out), it means that the last item added to the stack will be the first item to be removed.
|
||||
|
||||
Stack is based on two methods (functions)-
|
||||
|
||||
## push(element)
|
||||
|
||||
It adds "element" to the top of the stack.
|
||||
|
||||
For example: If we have `1, 3, 5` in stack, and we call push(9),
|
||||
|
||||
`9` will be added to last index of stack -> `1, 3, 5 , 9`.
|
||||
|
||||
## peek() or top()
|
||||
|
||||
It returns element at the top of the stack.
|
||||
|
||||
For example: If we have `1, 3, 5` in stack, and we call peek(),
|
||||
|
||||
`5` will be returned (without removing it from the stack).
|
||||
|
||||
## pop()
|
||||
|
||||
It removes the last element (i.e. top of stack) from stack.
|
||||
|
||||
For example: If we have `1, 3, 5 , 9` in stack, and we call pop(),
|
||||
|
||||
the function will return `9` and the stack will change to `1, 3, 5`.
|
@ -0,0 +1,70 @@
|
||||
package com.thealgorithms.datastructures.stacks;
|
||||
|
||||
import java.util.Scanner;
|
||||
import java.util.Stack;
|
||||
|
||||
/**
|
||||
* Reversal of a stack using recursion.
|
||||
*
|
||||
* @author Ishika Agarwal, 2021
|
||||
*/
|
||||
public class ReverseStack {
|
||||
|
||||
public static void main(String args[]) {
|
||||
|
||||
Scanner sc = new Scanner(System.in);
|
||||
System.out.println("Enter the number of elements you wish to insert in the stack");
|
||||
int n = sc.nextInt();
|
||||
int i;
|
||||
Stack<Integer> stack = new Stack<Integer>();
|
||||
System.out.println("Enter the stack elements");
|
||||
for (i = 0; i < n; i++) {
|
||||
stack.push(sc.nextInt());
|
||||
}
|
||||
sc.close();
|
||||
reverseStack(stack);
|
||||
System.out.println("The reversed stack is:");
|
||||
while (!stack.isEmpty()) {
|
||||
System.out.print(stack.peek() + ",");
|
||||
stack.pop();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static void reverseStack(Stack<Integer> stack) {
|
||||
if (stack.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
//Store the topmost element
|
||||
int element = stack.peek();
|
||||
//Remove the topmost element
|
||||
stack.pop();
|
||||
|
||||
//Reverse the stack for the leftover elements
|
||||
reverseStack(stack);
|
||||
|
||||
//Insert the topmost element to the bottom of the stack
|
||||
insertAtBottom(stack, element);
|
||||
|
||||
}
|
||||
|
||||
private static void insertAtBottom(Stack<Integer> stack, int element) {
|
||||
|
||||
if (stack.isEmpty()) {
|
||||
//When stack is empty, insert the element so it will be present at the bottom of the stack
|
||||
stack.push(element);
|
||||
return;
|
||||
}
|
||||
|
||||
int ele = stack.peek();
|
||||
/*Keep popping elements till stack becomes empty. Push the elements once the topmost element has
|
||||
moved to the bottom of the stack.
|
||||
*/
|
||||
stack.pop();
|
||||
insertAtBottom(stack, element);
|
||||
|
||||
stack.push(ele);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,173 @@
|
||||
package com.thealgorithms.datastructures.stacks;
|
||||
|
||||
/**
|
||||
* This class implements a Stack using a regular array.
|
||||
*
|
||||
* <p>
|
||||
* A stack is exactly what it sounds like. An element gets added to the top of
|
||||
* the stack and only the element on the top may be removed. This is an example
|
||||
* of an array implementation of a Stack. So an element can only be
|
||||
* added/removed from the end of the array. In theory stack have no fixed size,
|
||||
* but with an array implementation it does.
|
||||
*/
|
||||
public class StackArray {
|
||||
|
||||
/**
|
||||
* Driver Code
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
// Declare a stack of maximum size 4
|
||||
StackArray myStackArray = new StackArray(4);
|
||||
|
||||
assert myStackArray.isEmpty();
|
||||
assert !myStackArray.isFull();
|
||||
|
||||
// Populate the stack
|
||||
myStackArray.push(5);
|
||||
myStackArray.push(8);
|
||||
myStackArray.push(2);
|
||||
myStackArray.push(9);
|
||||
|
||||
assert !myStackArray.isEmpty();
|
||||
assert myStackArray.isFull();
|
||||
assert myStackArray.peek() == 9;
|
||||
assert myStackArray.pop() == 9;
|
||||
assert myStackArray.peek() == 2;
|
||||
assert myStackArray.size() == 3;
|
||||
}
|
||||
|
||||
/**
|
||||
* Default initial capacity.
|
||||
*/
|
||||
private static final int DEFAULT_CAPACITY = 10;
|
||||
|
||||
/**
|
||||
* The max size of the Stack
|
||||
*/
|
||||
private int maxSize;
|
||||
|
||||
/**
|
||||
* The array representation of the Stack
|
||||
*/
|
||||
private int[] stackArray;
|
||||
|
||||
/**
|
||||
* The top of the stack
|
||||
*/
|
||||
private int top;
|
||||
|
||||
/**
|
||||
* init Stack with DEFAULT_CAPACITY
|
||||
*/
|
||||
public StackArray() {
|
||||
this(DEFAULT_CAPACITY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param size Size of the Stack
|
||||
*/
|
||||
public StackArray(int size) {
|
||||
maxSize = size;
|
||||
stackArray = new int[maxSize];
|
||||
top = -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an element to the top of the stack
|
||||
*
|
||||
* @param value The element added
|
||||
*/
|
||||
public void push(int value) {
|
||||
if (!isFull()) { // Checks for a full stack
|
||||
top++;
|
||||
stackArray[top] = value;
|
||||
} else {
|
||||
resize(maxSize * 2);
|
||||
push(value); // don't forget push after resizing
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the top element of the stack and returns the value you've removed
|
||||
*
|
||||
* @return value popped off the Stack
|
||||
*/
|
||||
public int pop() {
|
||||
if (!isEmpty()) { // Checks for an empty stack
|
||||
return stackArray[top--];
|
||||
}
|
||||
|
||||
if (top < maxSize / 4) {
|
||||
resize(maxSize / 2);
|
||||
return pop(); // don't forget pop after resizing
|
||||
} else {
|
||||
System.out.println("The stack is already empty");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the element at the top of the stack
|
||||
*
|
||||
* @return element at the top of the stack
|
||||
*/
|
||||
public int peek() {
|
||||
if (!isEmpty()) { // Checks for an empty stack
|
||||
return stackArray[top];
|
||||
} else {
|
||||
System.out.println("The stack is empty, cant peek");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
private void resize(int newSize) {
|
||||
int[] transferArray = new int[newSize];
|
||||
|
||||
for (int i = 0; i < stackArray.length; i++) {
|
||||
transferArray[i] = stackArray[i];
|
||||
}
|
||||
// This reference change might be nice in here
|
||||
stackArray = transferArray;
|
||||
maxSize = newSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the stack is empty
|
||||
*
|
||||
* @return true if the stack is empty
|
||||
*/
|
||||
public boolean isEmpty() {
|
||||
return (top == -1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the stack is full
|
||||
*
|
||||
* @return true if the stack is full
|
||||
*/
|
||||
public boolean isFull() {
|
||||
return (top + 1 == maxSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes everything in the Stack
|
||||
*
|
||||
* <p>
|
||||
* Doesn't delete elements in the array but if you call push method after
|
||||
* calling makeEmpty it will overwrite previous values
|
||||
*/
|
||||
public void makeEmpty() { // Doesn't delete elements in the array but if you call
|
||||
top = -1; // push method after calling makeEmpty it will overwrite previous values
|
||||
}
|
||||
|
||||
/**
|
||||
* Return size of stack
|
||||
*
|
||||
* @return size of stack
|
||||
*/
|
||||
public int size() {
|
||||
return top + 1;
|
||||
}
|
||||
}
|
@ -0,0 +1,116 @@
|
||||
package com.thealgorithms.datastructures.stacks;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.EmptyStackException;
|
||||
|
||||
/**
|
||||
* This class implements a Stack using an ArrayList.
|
||||
*
|
||||
* <p>
|
||||
* A stack is exactly what it sounds like. An element gets added to the top of
|
||||
* the stack and only the element on the top may be removed.
|
||||
*
|
||||
* <p>
|
||||
* This is an ArrayList Implementation of a stack, where size is not a problem
|
||||
* we can extend the stack as much as we want.
|
||||
*/
|
||||
public class StackArrayList {
|
||||
|
||||
/**
|
||||
* Driver Code
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
StackArrayList stack = new StackArrayList();
|
||||
assert stack.isEmpty();
|
||||
|
||||
for (int i = 1; i <= 5; ++i) {
|
||||
stack.push(i);
|
||||
assert stack.size() == i;
|
||||
}
|
||||
|
||||
assert stack.size() == 5;
|
||||
assert stack.peek() == 5 && stack.pop() == 5 && stack.peek() == 4;
|
||||
|
||||
/* pop elements at the top of this stack one by one */
|
||||
while (!stack.isEmpty()) {
|
||||
stack.pop();
|
||||
}
|
||||
assert stack.isEmpty();
|
||||
|
||||
try {
|
||||
stack.pop();
|
||||
assert false;
|
||||
/* this should not happen */
|
||||
} catch (EmptyStackException e) {
|
||||
assert true;
|
||||
/* this should happen */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ArrayList representation of the stack
|
||||
*/
|
||||
private ArrayList<Integer> stack;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*/
|
||||
public StackArrayList() {
|
||||
stack = new ArrayList<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds value to the end of list which is the top for stack
|
||||
*
|
||||
* @param value value to be added
|
||||
*/
|
||||
public void push(int value) {
|
||||
stack.add(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the element at the top of this stack and returns
|
||||
*
|
||||
* @return Element popped
|
||||
* @throws EmptyStackException if the stack is empty.
|
||||
*/
|
||||
public int pop() {
|
||||
if (isEmpty()) {
|
||||
throw new EmptyStackException();
|
||||
}
|
||||
|
||||
/* remove the element on the top of the stack */
|
||||
return stack.remove(stack.size() - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test if the stack is empty.
|
||||
*
|
||||
* @return {@code true} if this stack is empty, {@code false} otherwise.
|
||||
*/
|
||||
public boolean isEmpty() {
|
||||
return stack.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the element at the top of this stack without removing it from the
|
||||
* stack.
|
||||
*
|
||||
* @return the element at the top of this stack.
|
||||
*/
|
||||
public int peek() {
|
||||
if (isEmpty()) {
|
||||
throw new EmptyStackException();
|
||||
}
|
||||
return stack.get(stack.size() - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return size of this stack.
|
||||
*
|
||||
* @return size of this stack.
|
||||
*/
|
||||
public int size() {
|
||||
return stack.size();
|
||||
}
|
||||
}
|
@ -0,0 +1,142 @@
|
||||
package com.thealgorithms.datastructures.stacks;
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
/**
|
||||
* @author Varun Upadhyay (https://github.com/varunu28)
|
||||
*/
|
||||
// An implementation of a Stack using a Linked List
|
||||
class StackOfLinkedList {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
LinkedListStack stack = new LinkedListStack();
|
||||
stack.push(1);
|
||||
stack.push(2);
|
||||
stack.push(3);
|
||||
stack.push(4);
|
||||
stack.push(5);
|
||||
|
||||
System.out.println(stack);
|
||||
|
||||
System.out.println("Size of stack currently is: " + stack.getSize());
|
||||
|
||||
assert stack.pop() == 5;
|
||||
assert stack.pop() == 4;
|
||||
|
||||
System.out.println("Top element of stack currently is: " + stack.peek());
|
||||
}
|
||||
}
|
||||
|
||||
// A node class
|
||||
class Node {
|
||||
|
||||
public int data;
|
||||
public Node next;
|
||||
|
||||
public Node(int data) {
|
||||
this.data = data;
|
||||
this.next = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A class which implements a stack using a linked list
|
||||
*
|
||||
* <p>
|
||||
* Contains all the stack methods : push, pop, printStack, isEmpty
|
||||
*/
|
||||
class LinkedListStack {
|
||||
|
||||
/**
|
||||
* Top of stack
|
||||
*/
|
||||
Node head;
|
||||
|
||||
/**
|
||||
* Size of stack
|
||||
*/
|
||||
private int size;
|
||||
|
||||
/**
|
||||
* Init properties
|
||||
*/
|
||||
public LinkedListStack() {
|
||||
head = null;
|
||||
size = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add element at top
|
||||
*
|
||||
* @param x to be added
|
||||
* @return <tt>true</tt> if add successfully
|
||||
*/
|
||||
public boolean push(int x) {
|
||||
Node newNode = new Node(x);
|
||||
newNode.next = head;
|
||||
head = newNode;
|
||||
size++;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pop element at top of stack
|
||||
*
|
||||
* @return element at top of stack
|
||||
* @throws NoSuchElementException if stack is empty
|
||||
*/
|
||||
public int pop() {
|
||||
if (size == 0) {
|
||||
throw new NoSuchElementException("Empty stack. Nothing to pop");
|
||||
}
|
||||
Node destroy = head;
|
||||
head = head.next;
|
||||
int retValue = destroy.data;
|
||||
destroy = null; // clear to let GC do it's work
|
||||
size--;
|
||||
return retValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Peek element at top of stack
|
||||
*
|
||||
* @return element at top of stack
|
||||
* @throws NoSuchElementException if stack is empty
|
||||
*/
|
||||
public int peek() {
|
||||
if (size == 0) {
|
||||
throw new NoSuchElementException("Empty stack. Nothing to pop");
|
||||
}
|
||||
return head.data;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
Node cur = head;
|
||||
StringBuilder builder = new StringBuilder();
|
||||
while (cur != null) {
|
||||
builder.append(cur.data).append("->");
|
||||
cur = cur.next;
|
||||
}
|
||||
return builder.replace(builder.length() - 2, builder.length(), "").toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if stack is empty
|
||||
*
|
||||
* @return <tt>true</tt> if stack is empty, otherwise <tt>false</tt>
|
||||
*/
|
||||
public boolean isEmpty() {
|
||||
return size == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return size of stack
|
||||
*
|
||||
* @return size of stack
|
||||
*/
|
||||
public int getSize() {
|
||||
return size;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user