preface
this article is about 300 lines of daily code link Study notes.
give a 10% discount, with a daily code of 30 lines.
this article adjusts the learned code according to your own understanding.
the code in this article is just personal notes, and some notes are jumping.
imitating excellent code is indeed the fastest way to learn programming.
day11 sequence table
in data structure, "abstract data type" is used to describe different data structures; In object-oriented programming, objects are used to store data and its operations; Their essence is common.
object: the sum of data and operations on it.
from the perspective of computer development, the first stage focuses on operation (function), such as a function for calculating missile trajectory, which obtains different outputs according to different inputs. The second stage focuses on data, that is, the data is stored in the database, and different algorithms are used to deal with it. The third stage considers that data and its operations are unified and inseparable, which leads to object-oriented.
packages are not necessary for programming. Their function is only to organize classes reasonably. But in the computer industry, often this dispensable thing is the most important, such as documents, comments and coding specifications. Dispensability is for the operation of the program, and its core is the computer; The most important thing is that for the readability and maintainability of the program, the core is the programmer.
let's talk about the basics: array initialization, 1 static initialization: int[] a={1,2,3}. 2 dynamic initialization: int[] b=new int[2]; b[0]=1; b[2]=2;. 3 default initialization. Default initialized element values of arrays of eight basic data types:
byte[] 0; int[] 0; short[] 0; long[] 0; double[] 0.0; float[] 0.0; boolean[] false; Char [] '\ u0000', \ u0000 is a placeholder in Unicode, and the default value of char [] can be understood as a space.
for String [], each element of the array is an object of String class, That is, each element is also a reference to data (the array variable must be a reference, that is, the manager of real data, such as String[] a = new String[3], int[] b = new int[3], then a and b refer to String array and int array respectively, but a[i] refers to a String and b[i] is an int), so the default initialization is not "", but null.
in another wordy sentence, the comparison between array variables is to judge whether the same array is managed, not whether the element values in the array are equal, such as int[] a ={1,2,3}; int[] b ={1,2,3}; System.out.println(a==b); The result is false. The assignment of array variables can only give management / reference permission, and cannot copy a new array with equal values.
therefore, to copy an array, you need to traverse the "source array" and copy each element to the "destination array" one by one.
similarly, if you want to judge whether the elements of two arrays are equal, you can't directly judge the "= =" of array variables, but write a loop to judge all elements one by one.
this section combines the first two parts of the original author into one section and gives a complete sequence table. The order table is implemented by array, that is, a fixed size array is given, and a part of the array is used to represent the linear table we need. The SequentialList class in this section rewrites the toString method to facilitate testing, and gives the following basic functions of the linear table:
- Construct initialization. There are two kinds: one is default initialization, and the other is to complete initialization according to the given array as a parameter;
- Reset the linear table and reset the actual array length to 0;
- Find the location of the given element. If it cannot be found, return - 1;
- Adds an element at a given location. If the linear table is full or the position is not within the existing position range, refuse to increase. Note, however, that this position can be one after the last element;
- Delete the element in the fixed position. Note that if the location is illegal, the location must have data.
The framework is given below:
public class SequentialList { private static final int MAX_LENGTH = 10; private int length; private int[] data; public SequentialList(); public SequentialList(int[] paraArray); public void reset(); public int locate(int paraValue); public boolean insert(int paraPosition, int paraValue); public boolean delete(int paraPosition); public String toString(); } // of class SequentialList
PS:
The data that method depends on includes both the data given in the parameter list and the member variables of the object. Therefore, the list of parameters involved in object-oriented is shorter. For example, the locate method makes effective use of the two member variables length and data.
for (int i = 10; I > 10; I --) {...} or for (int i = length; I < paralength; I + +) {...} when paraLength=length, such code will not report an error and will not run.
package dataStructure; /** * Sequential list. Name and comments follow the author's style strictly. * * @author Fan Min minfanphd@163.com. * @learner CatInCoffee. */ public class SequentialList { /** * The maximal length of the list. It is a constant. */ private static final int MAX_LENGTH = 10; /** * The actual length not exceeding MAX_LENGTH. Attention: length is not only the * member variable of Sequential list, but also the member variable of Array. In * fact, a name can be the member variable of different classes. */ private int length; /** * The data stored in an array. */ private int[] data; /** ********************* * Construct an empty sequential list. ********************* */ public SequentialList() { length = 0; data = new int[MAX_LENGTH]; } // Of the first constructor /** ********************* * Construct a sequential list using an array. * * @param paraArray The given array. Its length should not exceed MAX_LENGTH. * For simplicity now we do not check it. ********************* */ public SequentialList(int[] paraArray) { data = new int[MAX_LENGTH]; length = paraArray.length; // Copy data. for (int i = 0; i < paraArray.length; i++) { data[i] = paraArray[i]; } // Of for i } // Of the second constructor /** ********************* * Override the method<toString()> claimed in Object, the superclass of any * class. ********************* */ public String toString() { String resultString = ""; if (length == 0) { return "empty."; } // Of if for (int i = 0; i < length - 1; i++) { resultString += data[i] + ", "; } // Of for i resultString += data[length - 1]; return resultString; } // Of toString /** ********************* * Reset to empty. ********************* */ public void reset() { length = 0; } // Of reset /** ********************* * Locate the given value. If it appears in multiple positions, simply return * the first one. * * @param paraValue The given value. * @return The position. -1 for not found. ********************* */ public int locate(int paraValue) { int tempPosition = -1; for (int i = 0; i < length; i++) { if (data[i] == paraValue) { tempPosition = i; break; } // Of if } // Of for i return tempPosition; } // Of locate /** ********************* * Insert a value to a position. If the list is already full, do nothing. * * @param paraPosition The given position. * @param paraValue The given value. * @return Success or not. ********************* */ public boolean insert(int paraPosition, int paraValue) { if (length == MAX_LENGTH) { System.out.println("List is full."); return false; } // Of if if ((paraPosition < 0) || (paraPosition > length)) { System.out.println("The position " + paraPosition + " is out of bounds."); return false; } // Of if // From tail to head. for (int i = length; i > paraPosition; i--) { data[i] = data[i - 1]; } // Of for i data[paraPosition] = paraValue; length++; return true; } // Of insert /** ********************* * Delete a value at the specified position. * * @param paraPosition The given position. * @return Success or not. ********************* */ public boolean delete(int paraPosition) { if ((paraPosition < 0) || (paraPosition >= length)) { System.out.println("The position " + paraPosition + " is out of bounds."); return false; } // Of if // From head to tail. for (int i = paraPosition; i < length - 1; i++) { data[i] = data[i + 1]; } // Of for i length--; return true; }// Of delete /** ********************* * The entrance of the program. * * @param args Not used now. ********************* */ public static void main(String[] args) { int[] tempArray = { 6, 7, 4, 9 }; SequentialList tempFirstList = new SequentialList(tempArray); System.out.println("After being initialized, the list is: " + tempFirstList.toString()); System.out.println("Without the toString() method, the list also is: " + tempFirstList); int tempValue = 4; int tempPosition = tempFirstList.locate(tempValue); System.out.println("The position of " + tempValue + " is " + tempPosition); tempValue = 5; tempPosition = tempFirstList.locate(tempValue); System.out.println("The position of " + tempValue + " is " + tempPosition + "\n"); tempPosition = 2; tempValue = 8; tempFirstList.insert(tempPosition, tempValue); System.out.println( "After inserting " + tempValue + " to position " + tempPosition + ", the list is: " + tempFirstList); tempPosition = 8; tempValue = 10; tempFirstList.insert(tempPosition, tempValue); System.out.println( "After inserting " + tempValue + " to position " + tempPosition + ", the list is: " + tempFirstList); tempPosition = 3; tempFirstList.delete(tempPosition); System.out .println("After deleting data at position " + tempPosition + ", the list is: " + tempFirstList + "\n"); for (int i = 0; i < 8; i++) { if (tempFirstList.insert(i, i)) { System.out.println("After inserting " + i + " to position " + i + ", the list is: " + tempFirstList); } else { System.out.println("\t So that we cannot insert "+i+" to position "+i+"."); } // of if } // Of for i tempFirstList.reset(); System.out.println("After the reset() method, the list is: " + tempFirstList); } // of main } // of class SequentialList
result:
After being initialized, the list is: 6, 7, 4, 9 Without the toString() method, the list also is: 6, 7, 4, 9 The position of 4 is 2 The position of 5 is -1 After inserting 8 to position 2, the list is: 6, 7, 8, 4, 9 The position 8 is out of bounds. After inserting 10 to position 8, the list is: 6, 7, 8, 4, 9 After deleting data at position 3, the list is: 6, 7, 8, 9 After inserting 0 to position 0, the list is: 0, 6, 7, 8, 9 After inserting 1 to position 1, the list is: 0, 1, 6, 7, 8, 9 After inserting 2 to position 2, the list is: 0, 1, 2, 6, 7, 8, 9 After inserting 3 to position 3, the list is: 0, 1, 2, 3, 6, 7, 8, 9 After inserting 4 to position 4, the list is: 0, 1, 2, 3, 4, 6, 7, 8, 9 After inserting 5 to position 5, the list is: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 List is full. So that we cannot insert 6 to position 6. List is full. So that we cannot insert 7 to position 7. After the reset() method, the list is: empty.
day12 linked list
support the same operations as the sequence table: initialization, insertion, deletion, etc.
create a class for the node.
similarities and differences between reference and pointer: the former can only be used; The latter can support p + + dangerous operations.
the assignment of reference data type will not produce a new object space.
the difference between a linked list and a linear list during insertion and deletion: the linked list no longer moves elements, but only changes references (pointers).
note that the naming here is the same as Java Util packages are named the same as LinkedList, but they can run, that is, different packages can contain class files with the same name. Here is only a single linked list of int s, more generally a double linked list of < anytype >.
notice the two implementation forms of for loop and while in this Code:
public int indexOf(int paraValue) { int tempPosition = 0; // Node tempNodeAtPosition = header.next; // while (tempNodeAtPosition != tail) { // if (tempNodeAtPosition.data == paraValue) { // return tempPosition; // } // Of if // tempNodeAtPosition = tempNodeAtPosition.next; // tempPosition++; // } // Of while for (Node temp = header.next; temp != tail; temp = temp.next) { if (temp.data == paraValue) { return tempPosition; } // Of if tempPosition++; } // of for temp tempPosition = -1; return tempPosition; }// Of indexOf
the framework is as follows:
package dataStructure; import dataStructure.LinkedList; /** * Linked list. Name and comments follow the author's style strictly. * * @author Fan Min minfanphd@163.com. * @learner CatInCoffee. */ public class LinkedList { private class Node { public int data; public Node next; public Node(int paraValue) {}// Of Node's constructor }// Of class Node private int theSize; private Node header; private Node tail; public LinkedList() {} // Of the constructor private void doClear() {} // of doClear public String toString() {} // Of toString public void reset() {} // Of reset public int indexOf(int paraValue) {}// Of indexOf public boolean add(int paraPosition, int paraValue) {}// Of add private Node getNodeBeforePosition(int paraPosition, int lower, int upper) {} // of getNodeBeforePosition private boolean addAfter(Node paraNode, int paraValue) {} // of addAfter public boolean delete(int paraPosition) {}// Of delete private boolean deleteAfter(Node paraNode) {} // of delete }// Of class LinkedList
complete code:
package dataStructure; import dataStructure.LinkedList; /** * Linked list. Name and comments follow the author's style strictly. * * @author Fan Min minfanphd@163.com. * @learner CatInCoffee. */ public class LinkedList { private class Node { public int data; public Node next; public Node(int paraValue) { data = paraValue; next = null; }// Of Node's constructor }// Of class Node private int theSize; private Node header; private Node tail; public LinkedList() { doClear(); } // Of the constructor private void doClear() { header = new Node(0); tail = new Node(0); header.next = tail; theSize = 0; } // of doClear public String toString() { if (header.next == tail) { return "empty."; } // Of if String resultString = "{ "; Node tempNodeAtPosition = header.next; while (tempNodeAtPosition != tail) { resultString += tempNodeAtPosition.data + " "; tempNodeAtPosition = tempNodeAtPosition.next; } // Of while resultString += "}"; return resultString; } // Of toString public void reset() { doClear(); } // Of reset /** ********************* * indexOf the given value. If it appears in multiple positions, simply return * the first one. * * @param paraValue the given value. * @return The position. -1 for not found. ********************* */ public int indexOf(int paraValue) { int tempPosition = 0; Node tempNodeAtPosition = header.next; while (tempNodeAtPosition != tail) { if (tempNodeAtPosition.data == paraValue) { return tempPosition; } // Of if tempNodeAtPosition = tempNodeAtPosition.next; tempPosition++; } // Of while tempPosition = -1; return tempPosition; }// Of indexOf /** ********************* * add a value at the specified position. * * @param paraPosition The given position. * @param paraValue The given value. * @return Success or not. ********************* */ public boolean add(int paraPosition, int paraValue) { Node tempNodeBefore = getNodeBeforePosition(paraPosition, 0, theSize); return addAfter(tempNodeBefore , paraValue); }// Of add private Node getNodeBeforePosition(int paraPosition, int lower, int upper) { if (paraPosition< lower || paraPosition > upper) { System.out.println("The position " + paraPosition + " is illegal."); return null; } // Of if // tempNodeBeforePosition.next is the Node at the specified position. Node tempNodeBeforePosition = header; for (int i = 0; i < paraPosition; i++) { tempNodeBeforePosition = tempNodeBeforePosition.next; } // Of for i return tempNodeBeforePosition; } // of getNodeBeforePosition /** ********************* * Add a value after the specified Node. * * @param paraNode The given Node before the Node to be added. * @return Success or not. ********************* */ private boolean addAfter(Node paraNode, int paraValue) { if (paraNode == null) { return false; } else { Node tempNewNode = new Node(paraValue); tempNewNode.next = paraNode.next; paraNode.next = tempNewNode; theSize++; return true; } // of if-else } // of addAfter /** ********************* * Delete a value at the specified position. * * @param paraPosition The given position. * @return Success or not. ********************* */ public boolean delete(int paraPosition) { if (header.next == tail) { System.out.println("Cannot delete element from an empty list."); return false; } // Of if Node tempNodeBefore = getNodeBeforePosition(paraPosition, 0, theSize-1); return deleteAfter(tempNodeBefore); }// Of delete /** ********************* * Delete a value after the specified Node. * * @param paraNode The given Node before the Node to be deleted. * @return Success or not. ********************* */ private boolean deleteAfter(Node paraNode) { if (paraNode == null) { return false; } else { paraNode.next = paraNode.next.next; theSize--; return true; } // of if-else } // of delete public static void main(String args[]) { LinkedList tempFirstList = new LinkedList(); System.out.println("Initialized, the list is: " + tempFirstList.toString()); for (int i = 0; i < 5; i++) { tempFirstList.add(0, 4 - i); } // Of for i System.out.println("Add 0 1 2 3 4 successively, the list is: " + tempFirstList.toString()); System.out.println("Add 9 to position 6 could be: " + tempFirstList.add(6, 9) + ", and the List is " + tempFirstList.toString()); System.out.println("Add 9 to position 5 could be: " + tempFirstList.add(5, 9) + ", and the List is " + tempFirstList.toString()); System.out.println(); System.out.println("Delete the element at position 6 could be: " + tempFirstList.delete(6) + ", and the List is " + tempFirstList.toString()); System.out.println("Delete the element at position 0 could be: " + tempFirstList.delete(0) + ", and the List is " + tempFirstList.toString()); System.out.println("Delete the element at position 4 could be: " + tempFirstList.delete(4) + ", and the List is " + tempFirstList.toString()); System.out.println(); System.out.println("Delete the element in position 0 for 5 times, the lists in sequence are: "); for (int i = 0; i < 5; i++) { tempFirstList.delete(0); System.out.println(tempFirstList); } // Of for i }// Of main }// Of class LinkedList
results:
Initialized, the list is: empty. Add 0 1 2 3 4 successively, the list is: { 0 1 2 3 4 } The position 6 is illegal. Add 9 to position 6 could be: false, and the List is { 0 1 2 3 4 } Add 9 to position 5 could be: true, and the List is { 0 1 2 3 4 9 } The position 6 is illegal. Delete the element at position 6 could be: false, and the List is { 0 1 2 3 4 9 } Delete the element at position 0 could be: true, and the List is { 1 2 3 4 9 } Delete the element at position 4 could be: true, and the List is { 1 2 3 4 } Delete the element in position 0 for 5 times, the lists in sequence are: { 2 3 4 } { 3 4 } { 4 } empty. Cannot delete element from an empty list. empty.
day13 ArrayList learning
refer to data structure and algorithm analysis (Mark Allen Weiss 3rd Edition) and Java Util's ArrayList and LinkedList code, and then sort out ArrayList and LinkedList with your own understanding.
obviously, these two sections can't be read in one day
see:
About ArrayList.
day14 LinkedList learning
see:
About LinkedList.
day15 stack
here is the stack of char implemented by array. Naturally, it can also be realized by linked list, and more generally, it is about any type of stack. In addition, you can also add a peek() method to view the top element without pop-up, so that the pop() method can also call the peek() method when it is implemented.
the basic code is as follows:
package dataStructure; /** * Char Stack. Name and comments follow the author's style strictly. * * @author Fan Min minfanphd@163.com. * @learner CatInCoffee. */ public class CharStack { /** * The depth. */ public static final int MAX_DEPTH = 10; /** * The actual depth. */ int depth; /** * The data */ char[] data; /** ********************* * Construct an empty char stack. ********************* */ public CharStack() { depth = 0; data = new char[MAX_DEPTH]; } // Of the first constructor /** ********************* * Overrides the method claimed in Object, the superclass of any class. ********************* */ public String toString() { String resultString = ""; for (int i = 0; i < depth; i++) { resultString += data[i]; } // Of for i return resultString; } // Of toString /** ********************* * Pushes an item onto the top of this stack. * * @param paraChar The given char. * @return Success or not. ********************* */ public boolean push(char paraChar) { if (depth == MAX_DEPTH) { System.out.print("Stack is full."); return false; } // Of if data[depth] = paraChar; depth++; return true; } // Of push /** ********************* * Looks at the char at the top of this stack without removing it from the * stack. * * @return the object at the top of this stack. ********************* */ public char peek() { if (depth == 0) { System.out.print("Nothing to pop. "); return '\0'; } // of if return data[depth - 1]; } // of peek /** ********************* * Removes the char at the top of this stack and returns that char as the value * of this function. * * @return the char removed from the stack. ********************* */ public char pop() { char resultChar = peek(); if (depth > 0) { depth--; } // of if return resultChar; } // Of pop /** ********************* * The entrance of the program. * * @param args Not used now. ********************* */ public static void main(String args[]) { CharStack tempStack = new CharStack(); for (char ch = 'a'; ch < 'm'; ch++) { tempStack.push(ch); System.out.println("The current stack is: " + tempStack); } // Of for ch System.out.println(); char tempChar; for (int i = 0; i < 12; i++) { tempChar = tempStack.pop(); System.out.print("Poped: " + tempChar); System.out.println(" The current stack is: " + tempStack); } // Of for i } // of main } // of class CharStack
result:
The current stack is: a The current stack is: ab The current stack is: abc The current stack is: abcd The current stack is: abcde The current stack is: abcdef The current stack is: abcdefg The current stack is: abcdefgh The current stack is: abcdefghi The current stack is: abcdefghij Stack is full.The current stack is: abcdefghij Stack is full.The current stack is: abcdefghij Poped: j The current stack is: abcdefghi Poped: i The current stack is: abcdefgh Poped: h The current stack is: abcdefg Poped: g The current stack is: abcdef Poped: f The current stack is: abcde Poped: e The current stack is: abcd Poped: d The current stack is: abc Poped: c The current stack is: ab Poped: b The current stack is: a Poped: a The current stack is: Nothing to pop. Poped: The current stack is: Nothing to pop. Poped: The current stack is:
day16 stack: bracket matching
task description: check whether the parentheses of a string match. Matching means that each left bracket has a corresponding right bracket of the same type, and the left bracket cannot appear to the right of the right bracket. You can modify the test string to check the operation under different conditions.
only a bracketMatching method and the corresponding call statement in main are added on the basis of the code in the previous section.
other characters have no effect except for the parentheses of interest. Once a mismatch is found, it returns directly.
stack is the core data structure of the operating system. Because for computers, how to reduce the complexity of time and space is the king. Stack is a function provided by the operating system. With system support, it is natural, fast and efficient, but the disadvantage is that the storage space is not large enough; The heap is about the function of applying for memory and releasing memory. It is controlled by the program itself, and the speed here will be slower than that of the stack.
the code is as follows. Create a new class to test bracket matching, which is realized through switch case:
package dataStructure; /** 1. Check if the brackets match. 2. 3. @author Fan Min minfanphd@163.com. 4. @learner CatInCoffee. */ public class BracketMatching { /** ********************* * Is the bracket matching? * * @param paraString The given expression. * @return Match or not. ********************* */ public static boolean bracketMatching(String paraString) { // Step 1. Initialize the stack through pushing a '#' at the bottom. CharStack tempStack = new CharStack(); tempStack.push('#'); char tempChar; char tempPopedChar; // Step 2. Process the string. For a string, length() is a method // instead of a member variable. for (int i = 0; i < paraString.length(); i++) { tempChar = paraString.charAt(i); switch (tempChar) { case '(': case '[': case '{': tempStack.push(tempChar); break; case ')': tempPopedChar = tempStack.pop(); if (tempPopedChar != '(') { return false; } // Of if break; case ']': tempPopedChar = tempStack.pop(); if (tempPopedChar != '[') { return false; } // Of if break; case '}': tempPopedChar = tempStack.pop(); if (tempPopedChar != '{') { return false; } // Of if break; default: // Do nothing. }// Of switch } // Of for i tempPopedChar = tempStack.pop(); if (tempPopedChar != '#') { return false; } // Of if return true; }// Of bracketMatching public static void main(String[] args) { boolean tempMatch; String tempExpression; tempExpression = "[2 + (1 - 3)] * 4"; tempMatch = bracketMatching(tempExpression); System.out.println("Is the expression " + tempExpression + " bracket matching? " + tempMatch); tempExpression = "(a [b} c)"; tempMatch = bracketMatching(tempExpression); System.out.println("Is the expression " + tempExpression + " bracket matching? " + tempMatch); tempExpression = "(a)[b]{(c)d}"; tempMatch = bracketMatching(tempExpression); System.out.println("Is the expression " + tempExpression + " bracket matching? " + tempMatch); tempExpression = "{(}[)]"; tempMatch = bracketMatching(tempExpression); System.out.println("Is the expression " + tempExpression + " bracket matching? " + tempMatch); tempExpression = "{1024^2 / [(511 +1)^3 × 512 ]} = ?"; tempMatch = bracketMatching(tempExpression); System.out.println("Is the expression " + tempExpression + " bracket matching? " + tempMatch); } // of main } // of class BracketMatching
result:
Is the expression [2 + (1 - 3)] * 4 bracket matching? true Is the expression (a [b} c) bracket matching? false Is the expression (a)[b]{(c)d} bracket matching? true Is the expression {(}[)] bracket matching? false Is the expression {1024^2 / [(511 +1)^3 × 512 ]} = ? bracket matching? true
day17 stack: recursion
the system will build a stack for recursion. For example, for an accumulation program, the spatial complexity is
O
(
n
)
O(n)
O(n) (note that space, i.e. storage, is more complex in time complexity), because the stack will pop up only when paraN = 1.
Recursion is obviously not circular reasoning. In numerical calculation, it is the recursive formula in high school mathematics, but recursion is far more than used for numerical calculation. Here is just a brief description of recursion. Recursion requires:
- The basic case, that is, there is always a case that can be given without recursion. [required]
- Keep pushing forward. [required]
- It is assumed that every step of recursion can run. [basic assumptions mean that we don't have to track a large number of complex recursive calls. By default, the computer can handle these complex details]
- compound interest rule: when solving the same instance of a problem, do not do repetitive work in different recursive calls. [excellent design principle, can not meet the requirements of operation, but the space and time consumption will be greatly increased]
the following example is the simplest recursion, but it is not a well-designed recursion.
taking Fibonacci sequence as an example, assuming that f(5) is calculated, f(3) and f(4) need to be calculated, and f(2) and f(3) need to be calculated for f(4). Obviously, f(3) is repeatedly calculated. In fact, there are a lot of repeated calculations. Each branch needs to be divided to the benchmark case and then calculated back. The time complexity of implementing Fibonacci sequence by recursion is
O
(
1.61
8
n
)
O(1.618^n)
O(1.618n) (the proof is omitted. In short, the time of design calculation f(N) is
T
n
T_n
Tn, so
T
n
=
T
n
−
1
+
T
n
−
2
T_n=T_{n-1}+T_{n-2}
Tn = Tn − 1 + Tn − 2. The first two times are constant time, which is equivalent to finding Fibonacci sequence, which can be found in High School Mathematics). It can be seen that the time complexity is exponential.
package dataStructure; /** * Recursion. A method can (directly or indirectly) invoke itself. The system * automatically creates a stack for it. * * @author Fan Min minfanphd@163.com. * @learner CatInCoffee. */ public class Recursion { /** ********************* * Sum to N. No loop, however a stack is used. * * @param paraN The given value. * @return The sum. ********************* */ public static int sumToN(int paraN) { if (paraN <= 0) { // Basis. return 0; } // Of if return sumToN(paraN - 1) + paraN; }// Of sumToN /** ********************* * Fibonacci sequence. * * @param paraN The given value. * @return The sum. ********************* */ public static int fibonacci(int paraN) { if (paraN <= 0) { // Negative values are invalid. Index 0 corresponds to the first element 0. return 0; } if (paraN == 1) { // Basis. return 1; } // Of if return fibonacci(paraN - 1) + fibonacci(paraN - 2); }// Of fibonacci public static void main(String[] args) { int tempValue = 5; System.out.println("0 sum to " + tempValue + " = " + sumToN(tempValue)); tempValue = -2; System.out.println("0 sum to " + tempValue + " = " + sumToN(tempValue)); for (int i = 0; i <= 5; i++) { System.out.println("Fibonacci " + i + ": " + fibonacci(i)); } // Of for i } // of main }// of class Recursion
result:
0 sum to 5 = 15 0 sum to -2 = 0 Fibonacci 0: 0 Fibonacci 1: 1 Fibonacci 2: 1 Fibonacci 3: 2 Fibonacci 4: 3 Fibonacci 5: 5
day18 chain queue
only the tail is operated when entering the team, and only the head is operated when leaving the team.
header and tail are The index to calculate the header and the tail. Reason: header and tail will be added all the time. Instead of the real index, the real index is obtained through% modular operation.
that is, data[head]; It should be data[head% total_space];. Otherwise, an exception of arrayindexoutof boundsexception will appear.
from another angle, in java, a%b=a-a/b*b of an integer is two times of multiplication and one time of addition, which may keep int resultValue = data[head]; Unchanged, but in header + +; Add a judgment if (header == TOTAL_SPACE) {header = 0;}, That is, the loop is realized through an additional judgment, and all% modular operations are cancelled. The same is true in the tail part, but note that the implementation of toString needs to adjust the code (the header may be greater than the tail). Of course, the amount of computation saved is very small, and no modular operation looks clever, but the readability of the code is enhanced, and the number of modular operations is consciously controlled.
package dataStructure; /** about class author ... */ public class LinkedQueue { private static class Node { int data; Node next; public Node(int paraValue) { data = paraValue; next = null; }// Of the constructor }// Of class Node Node header; Node tail; public LinkedQueue() { doConstruct(); }// Of the first constructor private void doConstruct() { header = new Node(-1); tail = header; } // of doConstruct() public void enqueue(int paraValue) { Node tempNode = new Node(paraValue); tail.next = tempNode; tail = tempNode; }// Of enqueue public int dequeue() { // if (header.next == null) { if (header == tail) { System.out.println("No element in the queue"); return -1; } // Of if int resultValue = header.next.data; header.next = header.next.next; if (header.next == null) { doConstruct(); } // of if return resultValue; }// Of dequeue public String toString() { String resultString = "{ "; if (header == tail) { // if (header.next == null) { return "empty"; } // Of if // Node tempNode = header.next; // while (tempNode != null) { // resultString += tempNode.data + ", "; // tempNode = tempNode.next; // } // Of while for (Node tempNode = header.next; tempNode != null; tempNode = tempNode.next) { resultString += tempNode.data + " "; } // of for tempNode resultString += "}"; return resultString; }// Of toString public static void main(String args[]) { LinkedQueue tempQueue = new LinkedQueue(); System.out.println("Initialized, the list is: " + tempQueue.toString()); for (int i = 0; i < 5; i++) { tempQueue.enqueue(i + 1); } // Of for i System.out.println("Enqueued 1 to 5 successively, the queue is: " + tempQueue); tempQueue.dequeue(); System.out.println("Dequeued, the queue is: " + tempQueue); System.out.println(); int tempValue; for (int i = 0; i < 5; i++) { tempValue = tempQueue.dequeue(); System.out.println("Looped delete " + tempValue + ", the new queue is: " + tempQueue); } // Of for i for (int i = 1; i < 4; i++) { tempQueue.enqueue(i*10); System.out.println("Enqueued" + i*10 + ", the queue is: " + tempQueue); } // Of for i } // Of main } // Of class LinkedQueue
result:
Initialized, the list is: empty Enqueued 1 to 5 successively, the queue is: { 1 2 3 4 5 } Dequeued, the queue is: { 2 3 4 5 } Looped delete 2, the new queue is: { 3 4 5 } Looped delete 3, the new queue is: { 4 5 } Looped delete 4, the new queue is: { 5 } Looped delete 5, the new queue is: empty No element in the queue Looped delete -1, the new queue is: empty Enqueued10, the queue is: { 10 } Enqueued20, the queue is: { 10 20 } Enqueued30, the queue is: { 10 20 30 }
day19 circular queue
the core is to use the remainder operation% to complete the judgment of reaching the cycle.
leave an empty node for judgment. The traditional method is to increase the header and tail all the time, and then modular operation to the corresponding node. You can also add a judgment to control the modular operation in the code.
later, rewrite the code here as a generic class of any type, circlequeue < anytype >, and apply it to the character queue.
package dataStructure; /** * Circle int queue. * * @author Fan Min minfanphd@163.com. * @learner CatInCoffee. */ public class CircleIntQueue { /** * The total space. One space should never be used. */ public static final int TOTAL_SPACE = 10; int[] data; /** * The index of the header and the tail. */ int header; int tail; /** ******************* * The constructor ******************* */ public CircleIntQueue() { data = new int[TOTAL_SPACE]; header = 0; tail = 0; } // Of the constructor /** ********************* * Enqueue. * * @param paraValue The value of the new node. ********************* */ public void enqueue(int paraValue) { if ((tail + 1) % TOTAL_SPACE == header) { System.out.println("The queue is full."); return; } // Of if data[tail] = paraValue; tail++; if (tail == TOTAL_SPACE) { tail = 0; } // of if } // Of enqueue /** ********************* * Dequeue. * * @return The value at the header. ********************* */ public int dequeue() { if (header == tail) { System.out.println("There is no element in the queue."); return -1; } // Of if int resultValue = data[header]; header++; if (header == TOTAL_SPACE) { header = 0; } // of if return resultValue; } // Of dequeue /** ********************* * Overrides the method claimed in Object, the superclass of any class. ********************* */ public String toString() { String resultString = "{ "; if (header == tail) { return "empty."; } else if (header < tail) { for (int i = header; i < tail; i++) { resultString += data[i] + " "; } // Of for i } else { for (int i = header; i < TOTAL_SPACE; i++) { resultString += data[i] + " "; } // Of for i for (int j = 0; j < tail; j++) { resultString += data[j] + " "; } // Of for j // for (int k = header; k < tail + TOTAL_SPACE; k++) { // resultString += data[k % TOTAL_SPACE] + " "; // } // Of for k } // of if-elseIf-if resultString += "}"; return resultString; } // Of toString /** ********************* * The entrance of the program. * * @param args Not used now. ********************* */ public static void main(String args[]) { CircleIntQueue tempQueue = new CircleIntQueue(); System.out.println("Initialized, the list is: " + tempQueue); for (int i = 0; i < 5; i++) { tempQueue.enqueue(i); } // Of for i System.out.println("Enqueue, the queue is: " + tempQueue); int tempValue = tempQueue.dequeue(); System.out.println("Dequeue " + tempValue + ", the queue is: " + tempQueue); tempValue = tempQueue.dequeue(); System.out.println("Dequeue " + tempValue + ", the queue is: " + tempQueue); System.out.println(); for (int i = 0; i < 7; i++) { tempQueue.enqueue(i + 5); System.out.println("Enqueue, the queue is: " + tempQueue); } // Of for i System.out.println(); for (int i = 0; i < 9; i++) { tempQueue.dequeue(); } // Of for i System.out.println("Dequeue 9 elements , and the queue is: " + tempQueue); System.out.println(); tempQueue.dequeue(); System.out.println("Dequeue, the queue is: " + tempQueue); tempQueue.enqueue(10); System.out.println("Enqueue, the queue is: " + tempQueue); } // Of main } // Of CircleIntQueue
result:
Initialized, the list is: empty. Enqueue, the queue is: { 0 1 2 3 4 } Dequeue 0, the queue is: { 1 2 3 4 } Dequeue 1, the queue is: { 2 3 4 } Enqueue, the queue is: { 2 3 4 5 } Enqueue, the queue is: { 2 3 4 5 6 } Enqueue, the queue is: { 2 3 4 5 6 7 } Enqueue, the queue is: { 2 3 4 5 6 7 8 } Enqueue, the queue is: { 2 3 4 5 6 7 8 9 } Enqueue, the queue is: { 2 3 4 5 6 7 8 9 10 } The queue is full. Enqueue, the queue is: { 2 3 4 5 6 7 8 9 10 } Dequeue 9 elements , and the queue is: empty. There is no element in the queue. Dequeue, the queue is: empty. Enqueue, the queue is: { 10 }
rewrite it to the generic class CircleQueue and test it with character queue.
package dataStructure; public class CircleQueue<T> { public static final int TOTAL_SPACE = 6; private T[] data; // The index of the header and the tail. private int header; private int tail; public CircleQueue() { data = (T[]) (new Object[TOTAL_SPACE]); header = 0; tail = 0; } // Of the constructor public void enqueue(T paraValue) { if ((tail + 1) % TOTAL_SPACE == header) { System.out.println("The queue is full."); return; } // Of if data[tail] = paraValue; tail++; if (tail == TOTAL_SPACE) { tail = 0; } // of if } // Of enqueue public T dequeue() { if (header == tail) { System.out.println("There is no element in the queue."); return null; } // Of if T resultValue = data[header]; header++; if (header == TOTAL_SPACE) { header = 0; } // of if return resultValue; } // Of dequeue public String toString() { String resultString = "{ "; if (header == tail) { return "empty."; } else if (header < tail) { for (int i = header; i < tail; i++) { resultString += data[i] + " "; } // Of for i } else { for (int i = header; i < TOTAL_SPACE; i++) { resultString += data[i] + " "; } // Of for i for (int j = 0; j < tail; j++) { resultString += data[j] + " "; } // Of for j // for (int k = header; k < tail + TOTAL_SPACE; k++) { // resultString += data[k % TOTAL_SPACE] + " "; // } // Of for k } // of if-elseIf-if resultString += "}"; return resultString; } // Of toString public static void main(String args[]) { CircleQueue<Character> tempQueue = new CircleQueue<>(); System.out.println("Initialized, the TOTAL_SPACE is: " + TOTAL_SPACE + " , and the list is: " + tempQueue); for (char i = '0'; i < '4'; i++) { tempQueue.enqueue(i); } // Of for i System.out.println("Enqueue, the queue is: " + tempQueue); Character tempValue = tempQueue.dequeue(); System.out.println("Dequeue " + tempValue + ", the queue is: " + tempQueue); for (char i = 'a'; i < 'd'; i++) { tempQueue.enqueue(i); System.out.println("Enqueue, the queue is: " + tempQueue); } // Of for i System.out.println(); for (int i = 0; i < 6; i++) { tempValue = tempQueue.dequeue(); System.out.println("Dequeue " + tempValue + ", the queue is: " + tempQueue); } // Of for i System.out.println(); for (char i = 'A'; i <= 'F'; i++) { tempQueue.enqueue(i); System.out.println("Enqueue, the queue is: " + tempQueue); } // Of for i } // Of main } // Of CircleQueue<T>
result:
Initialized, the TOTAL_SPACE is: 6 , and the list is: empty. Enqueue, the queue is: { 0 1 2 3 } Dequeue 0, the queue is: { 1 2 3 } Enqueue, the queue is: { 1 2 3 a } Enqueue, the queue is: { 1 2 3 a b } The queue is full. Enqueue, the queue is: { 1 2 3 a b } Dequeue 1, the queue is: { 2 3 a b } Dequeue 2, the queue is: { 3 a b } Dequeue 3, the queue is: { a b } Dequeue a, the queue is: { b } Dequeue b, the queue is: empty. There is no element in the queue. Dequeue null, the queue is: empty. Enqueue, the queue is: { A } Enqueue, the queue is: { A B } Enqueue, the queue is: { A B C } Enqueue, the queue is: { A B C D } Enqueue, the queue is: { A B C D E } The queue is full. Enqueue, the queue is: { A B C D E }
day20 string match
printing quotation marks:\“
package dataStructure; /** about class author ... */ public class MyString { public static final int MAX_LENGTH = 10; private int length; private char[] data; public MyString() { doConstruct(); } // Of the first constructor private void doConstruct() { length = 0; data = new char[MAX_LENGTH]; } // of doConstruct() public MyString(String paraString) { if (paraString.length() > MAX_LENGTH) { System.out.println("The String <" + paraString + "> cannot be initialized."); doConstruct(); return; } // of if data = new char[MAX_LENGTH]; length = paraString.length(); for (int i = 0; i < length; i++) { data[i] = paraString.charAt(i); } // Of for i } // Of the second constructor public String toString() { String resultString = ""; for (int i = 0; i < length; i++) { resultString += data[i]; } // Of for i return resultString; } // Of toString /** ********************* * Locate the position of a substring. * * @param paraString The given substring. * @return The first position. -1 for no matching. ********************* */ public int locate(MyString paraMyString) { boolean tempMatch = false; for (int i = 0; i < length - paraMyString.length + 1; i++) { // Initialize. tempMatch = true; for (int j = 0; j < paraMyString.length; j++) { if (data[i + j] != paraMyString.data[j]) { tempMatch = false; break; } // Of if } // Of for j if (tempMatch) { return i; } // Of if } // Of for i return -1; } // Of locate /** ********************* * Get a substring * * @param paraString The given substring. * @param paraStartPosition The start position in the original string. * @param paraLength The length of the new string. * @return The first position. -1 for no matching. ********************* */ public MyString substring(int paraStartPosition, int paraLength) { if (paraStartPosition + paraLength > length) { System.out.print("The bound is exceeded. \t"); return null; } // Of if MyString resultMyString = new MyString(); resultMyString.length = paraLength; for (int i = 0; i < paraLength; i++) { resultMyString.data[i] = data[paraStartPosition + i]; } // Of for i return resultMyString; } // Of substring public static void main(String args[]) { MyString tempFirstString = new MyString("I like ik...."); tempFirstString = new MyString("I like iki"); MyString tempSecondString = new MyString("ik"); int tempPosition = tempFirstString.locate(tempSecondString); System.out.println( "The position of \"" + tempSecondString + "\" in \"" + tempFirstString + "\" is: " + tempPosition); MyString tempThirdString = new MyString("ki"); tempPosition = tempFirstString.locate(tempThirdString); System.out.println( "The position of \"" + tempThirdString + "\" in \"" + tempFirstString + "\" is: " + tempPosition); tempThirdString = new MyString("love"); tempPosition = tempFirstString.locate(tempThirdString); System.out.println( "The position of \"" + tempThirdString + "\" in \"" + tempFirstString + "\" is: " + tempPosition); tempThirdString = tempFirstString.substring(1, 2); System.out.println("The substring is: \"" + tempThirdString + "\""); tempThirdString = tempFirstString.substring(5, 5); System.out.println("The substring is: \"" + tempThirdString + "\""); tempThirdString = tempFirstString.substring(5, 6); System.out.println("The substring is: \"" + tempThirdString + "\""); } // Of main } // Of class MyString
result:
The String <I like ik....> cannot be initialized. The position of "ik" in "I like iki" is: 3 The position of "ki" in "I like iki" is: 8 The position of "love" in "I like iki" is: -1 The substring is: " l" The substring is: "e iki" The bound is exceeded. The substring is: "null"