mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-10 21:43:15 +08:00
Merge branch 'master' into master
This commit is contained in:
@ -54,20 +54,16 @@ public class SinglyLinkedList {
|
||||
* @param data data to be stored in a new node
|
||||
* @param position position at which a new node is to be inserted
|
||||
*/
|
||||
|
||||
public void insertNth(int data, int position) {
|
||||
if (position < 0 || position > getSize()) {
|
||||
throw new IndexOutOfBoundsException("position less than zero or position more than the count of list");
|
||||
} else {
|
||||
Node cur = head;
|
||||
Node node = new Node(data);
|
||||
for (int i = 0; i < position; ++i) {
|
||||
cur = cur.next;
|
||||
}
|
||||
node.next = cur.next;
|
||||
cur.next = node;
|
||||
size++;
|
||||
checkBounds(position, 0, size);
|
||||
Node cur = head;
|
||||
for (int i = 0; i < position; ++i) {
|
||||
cur = cur.next;
|
||||
}
|
||||
Node node = new Node(data);
|
||||
node.next = cur.next;
|
||||
cur.next = node;
|
||||
size++;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -90,20 +86,48 @@ public class SinglyLinkedList {
|
||||
* This method deletes an element at Nth position
|
||||
*/
|
||||
public void deleteNth(int position) {
|
||||
if (position < 0 || position > size - 1) {
|
||||
throw new IndexOutOfBoundsException("position less than zero or position more than the count of list");
|
||||
} else {
|
||||
Node cur = head;
|
||||
for (int i = 0; i < position; ++i) {
|
||||
cur = cur.next;
|
||||
}
|
||||
|
||||
Node destroy = cur.next;
|
||||
cur.next = cur.next.next;
|
||||
destroy = null; // clear to let GC do its work
|
||||
|
||||
size--;
|
||||
checkBounds(position, 0, size - 1);
|
||||
Node cur = head;
|
||||
for (int i = 0; i < position; ++i) {
|
||||
cur = cur.next;
|
||||
}
|
||||
|
||||
Node destroy = cur.next;
|
||||
cur.next = cur.next.next;
|
||||
destroy = null; // clear to let GC do its work
|
||||
|
||||
size--;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param position to check position
|
||||
* @param low low index
|
||||
* @param high high index
|
||||
* @throws IndexOutOfBoundsException if {@code position} not in range {@code low} to {@code high}
|
||||
*/
|
||||
public void checkBounds(int position, int low, int high) {
|
||||
if (position < low || position > high) {
|
||||
throw new IndexOutOfBoundsException(position + "");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* clear all nodes in list
|
||||
*/
|
||||
public void clear() {
|
||||
if (size == 0) {
|
||||
return;
|
||||
}
|
||||
Node prev = head.next;
|
||||
Node cur = prev.next;
|
||||
while (cur != null) {
|
||||
prev = null; // clear to let GC do its work
|
||||
prev = cur;
|
||||
cur = cur.next;
|
||||
}
|
||||
prev = null;
|
||||
head.next = null;
|
||||
size = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -115,18 +139,6 @@ public class SinglyLinkedList {
|
||||
return size == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints contents of the list
|
||||
*/
|
||||
public void display() {
|
||||
Node current = head.next;
|
||||
while (current != null) {
|
||||
System.out.print(current.value + " ");
|
||||
current = current.next;
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the size of the linked list
|
||||
*/
|
||||
@ -134,6 +146,20 @@ public class SinglyLinkedList {
|
||||
return size;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
if (size == 0) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder builder = new StringBuilder();
|
||||
Node cur = head.next;
|
||||
while (cur != null) {
|
||||
builder.append(cur.value).append("->");
|
||||
cur = cur.next;
|
||||
}
|
||||
return builder.replace(builder.length() - 2, builder.length(), "").toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Main method
|
||||
*
|
||||
@ -148,19 +174,24 @@ public class SinglyLinkedList {
|
||||
myList.insertHead(7);
|
||||
myList.insertHead(10);
|
||||
|
||||
myList.display(); // 10 -> 7 -> 5
|
||||
System.out.println(myList);; // 10 -> 7 -> 5
|
||||
|
||||
myList.deleteHead();
|
||||
|
||||
myList.display(); // 7 -> 5
|
||||
System.out.println(myList);; // 7 -> 5
|
||||
|
||||
myList.insertNth(11, 2);
|
||||
|
||||
myList.display(); // 7 -> 5 -> 11
|
||||
System.out.println(myList);; // 7 -> 5 -> 11
|
||||
|
||||
myList.deleteNth(1);
|
||||
|
||||
myList.display(); // 7-> 11
|
||||
System.out.println(myList);; // 7-> 11
|
||||
|
||||
myList.clear();
|
||||
assert myList.isEmpty();
|
||||
|
||||
System.out.println(myList); // ""
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -1,10 +1,8 @@
|
||||
package data_structures.Stacks;
|
||||
package DataStructures.Stacks;
|
||||
|
||||
import java.util.Scanner;
|
||||
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
|
||||
@ -15,71 +13,69 @@ import java.util.Stack;
|
||||
* returns true if S is nested and false otherwise.
|
||||
*
|
||||
* @author akshay sharma
|
||||
* @date: 2017-10-17
|
||||
* @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 s
|
||||
* @return
|
||||
* @param leftBracket left bracket
|
||||
* @param rightBracket right bracket
|
||||
* @return {@code true} if {@code leftBracket} and {@code rightBracket} is paired,
|
||||
* otherwise {@code false}
|
||||
*/
|
||||
static boolean is_balanced(String s) {
|
||||
Stack<Character> bracketsStack = new Stack<>();
|
||||
char[] text = s.toCharArray();
|
||||
for (char x : text) {
|
||||
switch (x) {
|
||||
case '{':
|
||||
case '<':
|
||||
case '(':
|
||||
case '[':
|
||||
bracketsStack.push(x);
|
||||
break;
|
||||
case '}':
|
||||
if (!bracketsStack.empty() && bracketsStack.pop() == '{') {
|
||||
break;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
case '>':
|
||||
if (!bracketsStack.empty() && bracketsStack.pop() == '<') {
|
||||
break;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
case ')':
|
||||
if (!bracketsStack.empty() && bracketsStack.pop() == '(') {
|
||||
break;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
case ']':
|
||||
if (!bracketsStack.empty() && bracketsStack.pop() == '[') {
|
||||
break;
|
||||
} else {
|
||||
return 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 bracketsStack.empty();
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if {@code brackets} is balanced
|
||||
*
|
||||
* @param args
|
||||
* @TODO remove main method and Test using JUnit or other methodology
|
||||
* @param brackets the brackets
|
||||
* @return {@code true} if {@code brackets} is balanced, otherwise {@code false}
|
||||
*/
|
||||
public static void main(String args[]) {
|
||||
try (Scanner in = new Scanner(System.in)) {
|
||||
System.out.println("Enter sequence of brackets: ");
|
||||
String s = in.nextLine();
|
||||
if (is_balanced(s)) {
|
||||
System.out.println(s + " is balanced");
|
||||
} else {
|
||||
System.out.println(s + " ain't balanced");
|
||||
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("[(])");
|
||||
}
|
||||
}
|
||||
|
44
DataStructures/Stacks/DecimalToAnyUsingStack.java
Normal file
44
DataStructures/Stacks/DecimalToAnyUsingStack.java
Normal file
@ -0,0 +1,44 @@
|
||||
package 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();
|
||||
}
|
||||
}
|
@ -17,12 +17,12 @@ class StackOfLinkedList {
|
||||
stack.push(4);
|
||||
stack.push(5);
|
||||
|
||||
stack.printStack();
|
||||
System.out.println(stack);
|
||||
|
||||
System.out.println("Size of stack currently is: " + stack.getSize());
|
||||
|
||||
stack.pop();
|
||||
stack.pop();
|
||||
assert stack.pop() == 5;
|
||||
assert stack.pop() == 4;
|
||||
|
||||
System.out.println("Top element of stack currently is: " + stack.peek());
|
||||
}
|
||||
@ -48,65 +48,95 @@ class Node {
|
||||
|
||||
class LinkedListStack {
|
||||
|
||||
Node head = null;
|
||||
/**
|
||||
* Top of stack
|
||||
*/
|
||||
Node head;
|
||||
|
||||
public void push(int x) {
|
||||
Node n = new Node(x);
|
||||
if (head == null) {
|
||||
head = n;
|
||||
} else {
|
||||
Node temp = head;
|
||||
n.next = temp;
|
||||
head = n;
|
||||
}
|
||||
/**
|
||||
* Size of stack
|
||||
*/
|
||||
private int size;
|
||||
|
||||
/**
|
||||
* Init properties
|
||||
*/
|
||||
public LinkedListStack() {
|
||||
head = null;
|
||||
size = 0;
|
||||
}
|
||||
|
||||
public void pop() {
|
||||
if (head == null) {
|
||||
System.out.println("Empty stack. Nothing to pop");
|
||||
}
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
Node temp = head;
|
||||
/**
|
||||
* 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;
|
||||
System.out.println("Popped element is: " + temp.data);
|
||||
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 (head == null) {
|
||||
return -1;
|
||||
if (size == 0) {
|
||||
throw new NoSuchElementException("Empty stack. Nothing to pop");
|
||||
}
|
||||
return head.data;
|
||||
}
|
||||
|
||||
public void printStack() {
|
||||
Node temp = head;
|
||||
System.out.println("Stack is printed as below: ");
|
||||
while (temp != null) {
|
||||
if (temp.next == null) {
|
||||
System.out.print(temp.data);
|
||||
} else {
|
||||
System.out.print(temp.data + " -> ");
|
||||
}
|
||||
temp = temp.next;
|
||||
@Override
|
||||
public String toString() {
|
||||
Node cur = head;
|
||||
StringBuilder builder = new StringBuilder();
|
||||
while (cur != null) {
|
||||
builder.append(cur.data).append("->");
|
||||
cur = cur.next;
|
||||
}
|
||||
System.out.println();
|
||||
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 head == null;
|
||||
return size == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return size of stack
|
||||
*
|
||||
* @return size of stack
|
||||
*/
|
||||
public int getSize() {
|
||||
if (head == null)
|
||||
return 0;
|
||||
else {
|
||||
int size = 1;
|
||||
Node temp = head;
|
||||
while (temp.next != null) {
|
||||
temp = temp.next;
|
||||
size++;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
}
|
||||
|
@ -12,6 +12,7 @@ public class Fibonacci {
|
||||
|
||||
private static Map<Integer, Integer> map = new HashMap<>();
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
// Methods all returning [0, 1, 1, 2, 3, 5, ...] for n = [0, 1, 2, 3, 4, 5, ...]
|
||||
|
@ -26,7 +26,8 @@ public class RodCutting {
|
||||
public static void main(String args[]) {
|
||||
int[] arr = new int[]{2, 5, 13, 19, 20};
|
||||
int size = arr.length;
|
||||
int result = cutRod(arr,size);
|
||||
System.out.println("Maximum Obtainable Value is " +
|
||||
cutRod(arr, size));
|
||||
result);
|
||||
}
|
||||
}
|
||||
|
@ -9,7 +9,7 @@ public class FindMin {
|
||||
}
|
||||
|
||||
/**
|
||||
* find min of array
|
||||
* Find the minimum number of an array of numbers.
|
||||
*
|
||||
* @param array the array contains element
|
||||
* @return min value
|
||||
|
30
Maths/PalindromeNumber.java
Normal file
30
Maths/PalindromeNumber.java
Normal file
@ -0,0 +1,30 @@
|
||||
package Maths;
|
||||
|
||||
public class PalindromeNumber {
|
||||
public static void main(String[] args) {
|
||||
|
||||
assert isPalindrome(12321);
|
||||
assert !isPalindrome(1234);
|
||||
assert isPalindrome(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if {@code n} is palindrome number or not
|
||||
*
|
||||
* @param number the number
|
||||
* @return {@code true} if {@code n} is palindrome number, otherwise {@code false}
|
||||
*/
|
||||
public static boolean isPalindrome(int number) {
|
||||
if (number < 0) {
|
||||
throw new IllegalArgumentException(number + "");
|
||||
}
|
||||
int numberCopy = number;
|
||||
int reverseNumber = 0;
|
||||
while (numberCopy != 0) {
|
||||
int remainder = numberCopy % 10;
|
||||
reverseNumber = reverseNumber * 10 + remainder;
|
||||
numberCopy /= 10;
|
||||
}
|
||||
return number == reverseNumber;
|
||||
}
|
||||
}
|
33
Maths/ParseInteger.java
Normal file
33
Maths/ParseInteger.java
Normal file
@ -0,0 +1,33 @@
|
||||
package Maths;
|
||||
|
||||
public class ParseInteger {
|
||||
public static void main(String[] args) {
|
||||
assert parseInt("123") == Integer.parseInt("123");
|
||||
assert parseInt("-123") == Integer.parseInt("-123");
|
||||
assert parseInt("0123") == Integer.parseInt("0123");
|
||||
assert parseInt("+123") == Integer.parseInt("+123");
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a string to integer
|
||||
*
|
||||
* @param s the string
|
||||
* @return the integer value represented by the argument in decimal.
|
||||
* @throws NumberFormatException if the {@code string} does not contain a parsable integer.
|
||||
*/
|
||||
public static int parseInt(String s) {
|
||||
if (s == null) {
|
||||
throw new NumberFormatException("null");
|
||||
}
|
||||
boolean isNegative = s.charAt(0) == '-';
|
||||
boolean isPositive = s.charAt(0) == '+';
|
||||
int number = 0;
|
||||
for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) {
|
||||
if (!Character.isDigit(s.charAt(i))) {
|
||||
throw new NumberFormatException("s=" + s);
|
||||
}
|
||||
number = number * 10 + s.charAt(i) - '0';
|
||||
}
|
||||
return isNegative ? -number : number;
|
||||
}
|
||||
}
|
33
Maths/PerfectNumber.java
Normal file
33
Maths/PerfectNumber.java
Normal file
@ -0,0 +1,33 @@
|
||||
package Maths;
|
||||
|
||||
/**
|
||||
* In number theory, a perfect number is a positive integer that is equal to the sum of
|
||||
* its positive divisors, excluding the number itself. For instance, 6 has divisors 1, 2 and 3
|
||||
* (excluding itself), and 1 + 2 + 3 = 6, so 6 is a perfect number.
|
||||
* <p>
|
||||
* link:https://en.wikipedia.org/wiki/Perfect_number
|
||||
* </p>
|
||||
*/
|
||||
public class PerfectNumber {
|
||||
public static void main(String[] args) {
|
||||
assert isPerfectNumber(6); /* 1 + 2 + 3 == 6 */
|
||||
assert !isPerfectNumber(8); /* 1 + 2 + 4 != 8 */
|
||||
assert isPerfectNumber(28); /* 1 + 2 + 4 + 7 + 14 == 28 */
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if {@code number} is perfect number or not
|
||||
*
|
||||
* @param number the number
|
||||
* @return {@code true} if {@code number} is perfect number, otherwise false
|
||||
*/
|
||||
public static boolean isPerfectNumber(int number) {
|
||||
int sum = 0; /* sum of its positive divisors */
|
||||
for (int i = 1; i < number; ++i) {
|
||||
if (number % i == 0) {
|
||||
sum += i;
|
||||
}
|
||||
}
|
||||
return sum == number;
|
||||
}
|
||||
}
|
26
Maths/Pow.java
Normal file
26
Maths/Pow.java
Normal file
@ -0,0 +1,26 @@
|
||||
package maths;
|
||||
|
||||
public class Pow {
|
||||
public static void main(String[] args) {
|
||||
assert pow(2, 0) == Math.pow(2, 0);
|
||||
assert pow(0, 2) == Math.pow(0, 2);
|
||||
assert pow(2, 10) == Math.pow(2, 10);
|
||||
assert pow(10, 2) == Math.pow(10, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of the first argument raised to the power of the
|
||||
* second argument
|
||||
*
|
||||
* @param a the base.
|
||||
* @param b the exponent.
|
||||
* @return the value {@code a}<sup>{@code b}</sup>.
|
||||
*/
|
||||
public static long pow(int a, int b) {
|
||||
long result = 1;
|
||||
for (int i = 1; i <= b; i++) {
|
||||
result *= a;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
26
Maths/PowRecursion.java
Normal file
26
Maths/PowRecursion.java
Normal file
@ -0,0 +1,26 @@
|
||||
package Maths;
|
||||
|
||||
public class PowRecursion {
|
||||
public static void main(String[] args) {
|
||||
assert pow(2, 0) == Math.pow(2, 0);
|
||||
assert pow(0, 2) == Math.pow(0, 2);
|
||||
assert pow(2, 10) == Math.pow(2, 10);
|
||||
assert pow(10, 2) == Math.pow(10, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of the first argument raised to the power of the
|
||||
* second argument
|
||||
*
|
||||
* @param a the base.
|
||||
* @param b the exponent.
|
||||
* @return the value {@code a}<sup>{@code b}</sup>.
|
||||
*/
|
||||
public static long pow(int a, int b) {
|
||||
if (b == 0) {
|
||||
return 1;
|
||||
} else {
|
||||
return a * pow(a, b - 1);
|
||||
}
|
||||
}
|
||||
}
|
@ -44,7 +44,5 @@ public class CountWords {
|
||||
}
|
||||
s = sb.toString();
|
||||
return s.trim().split("[\\s]+").length;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
Reference in New Issue
Block a user