Merge branch 'master' into master

This commit is contained in:
Yang Libin
2019-10-24 14:39:48 +08:00
committed by GitHub
13 changed files with 391 additions and 142 deletions

View File

@ -54,21 +54,17 @@ public class SinglyLinkedList {
* @param data data to be stored in a new node * @param data data to be stored in a new node
* @param position position at which a new node is to be inserted * @param position position at which a new node is to be inserted
*/ */
public void insertNth(int data, int position) { public void insertNth(int data, int position) {
if (position < 0 || position > getSize()) { checkBounds(position, 0, size);
throw new IndexOutOfBoundsException("position less than zero or position more than the count of list");
} else {
Node cur = head; Node cur = head;
Node node = new Node(data);
for (int i = 0; i < position; ++i) { for (int i = 0; i < position; ++i) {
cur = cur.next; cur = cur.next;
} }
Node node = new Node(data);
node.next = cur.next; node.next = cur.next;
cur.next = node; cur.next = node;
size++; size++;
} }
}
/** /**
* This method deletes an element at the head * This method deletes an element at the head
@ -90,9 +86,7 @@ public class SinglyLinkedList {
* This method deletes an element at Nth position * This method deletes an element at Nth position
*/ */
public void deleteNth(int position) { public void deleteNth(int position) {
if (position < 0 || position > size - 1) { checkBounds(position, 0, size - 1);
throw new IndexOutOfBoundsException("position less than zero or position more than the count of list");
} else {
Node cur = head; Node cur = head;
for (int i = 0; i < position; ++i) { for (int i = 0; i < position; ++i) {
cur = cur.next; cur = cur.next;
@ -104,6 +98,36 @@ public class SinglyLinkedList {
size--; 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; 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 * Returns the size of the linked list
*/ */
@ -134,6 +146,20 @@ public class SinglyLinkedList {
return size; 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 * Main method
* *
@ -148,19 +174,24 @@ public class SinglyLinkedList {
myList.insertHead(7); myList.insertHead(7);
myList.insertHead(10); myList.insertHead(10);
myList.display(); // 10 -> 7 -> 5 System.out.println(myList);; // 10 -> 7 -> 5
myList.deleteHead(); myList.deleteHead();
myList.display(); // 7 -> 5 System.out.println(myList);; // 7 -> 5
myList.insertNth(11, 2); myList.insertNth(11, 2);
myList.display(); // 7 -> 5 -> 11 System.out.println(myList);; // 7 -> 5 -> 11
myList.deleteNth(1); myList.deleteNth(1);
myList.display(); // 7-> 11 System.out.println(myList);; // 7-> 11
myList.clear();
assert myList.isEmpty();
System.out.println(myList); // ""
} }
} }

View File

@ -1,10 +1,8 @@
package data_structures.Stacks; package DataStructures.Stacks;
import java.util.Scanner;
import java.util.Stack; import java.util.Stack;
/** /**
*
* The nested brackets problem is a problem that determines if a sequence of * 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 * 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 * 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. * returns true if S is nested and false otherwise.
* *
* @author akshay sharma * @author akshay sharma
* @date: 2017-10-17
* @author <a href="https://github.com/khalil2535">khalil2535<a> * @author <a href="https://github.com/khalil2535">khalil2535<a>
* * @author shellhub
*/ */
class BalancedBrackets { class BalancedBrackets {
/** /**
* Check if {@code leftBracket} and {@code rightBracket} is paired or not
* *
* @param s * @param leftBracket left bracket
* @return * @param rightBracket right bracket
* @return {@code true} if {@code leftBracket} and {@code rightBracket} is paired,
* otherwise {@code false}
*/ */
static boolean is_balanced(String s) { public static boolean isPaired(char leftBracket, char rightBracket) {
Stack<Character> bracketsStack = new Stack<>(); char[][] pairedBrackets = {
char[] text = s.toCharArray(); {'(', ')'},
for (char x : text) { {'[', ']'},
switch (x) { {'{', '}'},
case '{': {'<', '>'}
case '<': };
case '(': for (char[] pairedBracket : pairedBrackets) {
case '[': if (pairedBracket[0] == leftBracket && pairedBracket[1] == rightBracket) {
bracketsStack.push(x); return true;
break; }
case '}': }
if (!bracketsStack.empty() && bracketsStack.pop() == '{') {
break;
} else {
return false; 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;
}
}
}
return bracketsStack.empty();
}
/** /**
* Check if {@code brackets} is balanced
* *
* @param args * @param brackets the brackets
* @TODO remove main method and Test using JUnit or other methodology * @return {@code true} if {@code brackets} is balanced, otherwise {@code false}
*/ */
public static void main(String args[]) { public static boolean isBalanced(String brackets) {
try (Scanner in = new Scanner(System.in)) { if (brackets == null) {
System.out.println("Enter sequence of brackets: "); throw new IllegalArgumentException("brackets is null");
String s = in.nextLine(); }
if (is_balanced(s)) { Stack<Character> bracketsStack = new Stack<>();
System.out.println(s + " is balanced"); for (char bracket : brackets.toCharArray()) {
} else { switch (bracket) {
System.out.println(s + " ain't balanced"); 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("[(])");
} }
} }

View 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();
}
}

View File

@ -17,12 +17,12 @@ class StackOfLinkedList {
stack.push(4); stack.push(4);
stack.push(5); stack.push(5);
stack.printStack(); System.out.println(stack);
System.out.println("Size of stack currently is: " + stack.getSize()); System.out.println("Size of stack currently is: " + stack.getSize());
stack.pop(); assert stack.pop() == 5;
stack.pop(); assert stack.pop() == 4;
System.out.println("Top element of stack currently is: " + stack.peek()); System.out.println("Top element of stack currently is: " + stack.peek());
} }
@ -48,65 +48,95 @@ class Node {
class LinkedListStack { class LinkedListStack {
Node head = null; /**
* Top of stack
*/
Node head;
public void push(int x) { /**
Node n = new Node(x); * Size of stack
if (head == null) { */
head = n; private int size;
} else {
Node temp = head; /**
n.next = temp; * Init properties
head = n; */
} public LinkedListStack() {
head = null;
size = 0;
} }
public void pop() { /**
if (head == null) { * Add element at top
System.out.println("Empty stack. Nothing to pop"); *
* @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; 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() { public int peek() {
if (head == null) { if (size == 0) {
return -1; throw new NoSuchElementException("Empty stack. Nothing to pop");
} }
return head.data; return head.data;
} }
public void printStack() { @Override
Node temp = head; public String toString() {
System.out.println("Stack is printed as below: "); Node cur = head;
while (temp != null) { StringBuilder builder = new StringBuilder();
if (temp.next == null) { while (cur != null) {
System.out.print(temp.data); builder.append(cur.data).append("->");
} else { cur = cur.next;
System.out.print(temp.data + " -> ");
} }
temp = temp.next; return builder.replace(builder.length() - 2, builder.length(), "").toString();
}
System.out.println();
} }
/**
* Check if stack is empty
*
* @return <tt>true</tt> if stack is empty, otherwise <tt>false</tt>
*/
public boolean isEmpty() { public boolean isEmpty() {
return head == null; return size == 0;
} }
/**
* Return size of stack
*
* @return size of stack
*/
public int getSize() { 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;
} }
}
} }

View File

@ -12,6 +12,7 @@ public class Fibonacci {
private static Map<Integer, Integer> map = new HashMap<>(); private static Map<Integer, Integer> map = new HashMap<>();
public static void main(String[] args) { public static void main(String[] args) {
// Methods all returning [0, 1, 1, 2, 3, 5, ...] for n = [0, 1, 2, 3, 4, 5, ...] // Methods all returning [0, 1, 1, 2, 3, 5, ...] for n = [0, 1, 2, 3, 4, 5, ...]

View File

@ -26,7 +26,8 @@ public class RodCutting {
public static void main(String args[]) { public static void main(String args[]) {
int[] arr = new int[]{2, 5, 13, 19, 20}; int[] arr = new int[]{2, 5, 13, 19, 20};
int size = arr.length; int size = arr.length;
int result = cutRod(arr,size);
System.out.println("Maximum Obtainable Value is " + System.out.println("Maximum Obtainable Value is " +
cutRod(arr, size)); result);
} }
} }

View File

@ -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 * @param array the array contains element
* @return min value * @return min value

View 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
View 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
View 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
View 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
View 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);
}
}
}

View File

@ -44,7 +44,5 @@ public class CountWords {
} }
s = sb.toString(); s = sb.toString();
return s.trim().split("[\\s]+").length; return s.trim().split("[\\s]+").length;
} }
} }