I Learning outline of data structure and algorithm
1. Data structure and algorithm learning outline
2. Linear structure classification
3. Characteristics and usage scenarios of various linear data structures
Array:
Features: the elements are stored linearly and continuously in memory, and the array elements can be accessed quickly according to the subscript, but the addition and deletion efficiency is not very high. It is necessary to add or delete elements every time
Move a large number of elements to empty the insertion position or fill the position of deleted elements.
Usage scenario: frequent queries and few additions or deletions
Linked list:
Features: the storage can be incoherent, and the data can be linked according to the index. When querying elements, you need to query from the beginning, so the efficiency is relatively low. However, it can be added or deleted
Element, you only need to modify the index.
Usage scenario: less queries and frequent inserts or deletions
Queue:
Features: FIFO / fisrt in first out, like a one-way tunnel, first in first out.
Usage scenario: multithreaded blocking queue management is very useful
Stack:
Features: LIFO / last in first out is like a box. The things put in first are at the bottom. You need to take out the things above first, and the things below can be taken out
Usage scenario: realize recursion and expression calculation. android uses the principle of stack to realize back stack
4. The difference between array and linked list
(1) Array continuous, linked list discontinuous
(2) Array memory static allocation, linked list memory dynamic allocation
(3) The time complexity of array query is O(1), and the linked list is 0(n)
(4) The time complexity of adding and deleting the array is O(n), and the linked list is O(1)
(5) The array allocates space from the stack and the linked list allocates space from the heap
II Array array of Java data structures and algorithms
1. Array overview
Array is one of the important data structures. It uses linear structure to store a fixed number of data with the same size and data type
2. Initialization of arrays in Java
(1) Declaration and initialization are separated
//statement //int[] a; int a[]; //Apply for space. The default initial value of int array is 0 a= new int[5]; //Initialization based on single assignment of subscript a[0] = 2; //Cyclic assignment for (int i = 0; i < a.length; i++) { a[i] = i; }
(2) Declaration initialization occurs at the same time
//int [] c ={1,3,4,5,6}; //int c[] ={1,3,4,5,6}; int c[] = new int[]{1,3,4,5,6};
3. API for arrays in Java
(1) Inheritance relationship of array class Arrays in Java
java.lang.Object java.util.Arrays
(2) Common methods
asList(T... a) / / convert the input parameters into List type data
binarySearch(Object[] a, Object key) / / find the specified element in the specified array through the binary search method, and return the subscript
copyOf(Object[] original, int newLength) / / copy the array to another array
copyOfRange(Object[] original, int from, int to) / / copy the given interval elements of the given array to the new array
equals(Object[] a, Object[] a2) / / judge whether the two arrays are equal, that is, whether the length and element value are consistent
deepEquals(Object[] a1, Object[] a2) / / commonly used to compare multidimensional arrays
fill(Object[] a, Object val) / / allocate the specified basic data type value to each item of the specified basic type array
fill(Object[] a, int fromIndex, int toIndex, Object val) / / specify the allocation to the specified interval
sort(Object[] a) / / sort in ascending order
sort(Object[] a, int fromIndex, int toIndex) / / specify the array range to be sorted
toString(Object[] a) / / convert to string type
4. Array sorting
PS: there are two methods for sorting arrays in Java. The first method is to directly use the sort(Object[] a) method in the API or the sort method in the algorithm
Various algorithms, such as bubble sort, selection sort, insertion sort, merge sort, etc.
(1)API sorting case
package com.datastructure.test; import java.util.Arrays; import java.util.List; public class ApiArray { public static void main(String[] args){ int[] a = {4,6,78,8,34,56,26}; sortByApi(a); } /* * Sorting arrays directly through api */ public static void sortByApi(int[] a){ System.out.println("Array before sorting:"); for (int i = 0; i < a.length; i++) { System.out.print(a[i]+"\t"); } System.out.println(); Arrays.sort(a); System.out.println("Sorted array:"); for (int i = 0; i < a.length; i++) { System.out.print(a[i]+"\t"); } } }
Console output:
Array before sorting: 4 6 78 8 34 56 26 Sorted array: 4 6 8 26 34 56 78
(2) Bubble sorting algorithm
package com.datastructure.test; import java.util.Arrays; import java.util.List; public class ApiArray { public static void main(String[] args){ int[] a = {4,6,78,8,34,56,26,2}; sortByBubble(a); } /* * Bubble sorting */ public static void sortByBubble(int[] a){ int temp,i,j; System.out.println("Array before sorting:"); for (i = 0; i < a.length; i++) { System.out.print(a[i]+"\t"); } for (i = 1; i < a.length; i++) { for (j = 0; j < a.length-i; j++) { if (a[j]>a[j+1]) { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } System.out.println(); System.out.println("Sorted array:"); for (i = 0; i < a.length; i++) { System.out.print(a[i]+"\t"); } } }
5. String to array (char[]/int [])
(1) String to char []
str="hellomynameisAndy"; char [] charArray = str.toCharArray();
(2) String to int []
package com.datastructure.test; public class Array { public static void main(String[] args) { StringToArray("1234"); } /* * String to int array, where string is required to be all numeric values */ public static void StringToArray(String str){ char[] ch; int [] i; int len; //string length len = str.trim().length(); //Initialize int array i=new int[len]; //Obtain a single character through charAt() and convert it to String type, and then convert it to int type through parseInt() for (int j = 0; j < len; j++) { i[j] =Integer.parseInt(String.valueOf(str.charAt(j))); } //int array output System.out.println("int Array output:"); for (int j = 0; j < i.length; j++) { System.out.print(i[j]+"\t"); } } }
6. Operation of two-dimensional array
(1) Declaration of two-dimensional array (taking int array as an example)
int a[][]; int [][] b;
(2) Initialization of two-dimensional array
int a[][]; a = new int[][]{{12,3,34},{23,34,56,78}}; int[][] c ={{1,2,3},{34,55,6},{45,678,89}}; int [][] b; b=new int[2][3]; b[0][0] = 1; b[0][1] = 2; b[0][2] = 5; b[1][0] = 10; b[1][1] = 34; b[1][2] = 35;
(3) Length calculation of two-dimensional array
//How many lines are calculated array.length //Calculate how many elements per line array[0].length
(4) Traversal of two-dimensional array
package com.datastructure.test; public class TwoDimensionalArray { public static void main(String[] args){ int row,col; //Note that when initializing characters or strings, remember to use quotation marks int[][] c ={{1,2,3},{34,55,6},{45,678,89}}; //Calculate the number of rows and columns. If you know it, you don't need it row = c.length; col = c[0].length; System.out.println("Two dimensional array traversal output:"); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { System.out.print(c[i][j]+"\t"); } System.out.println(); } } }
Console output results:
Two dimensional array traversal output: 1 2 3 34 55 6 45 678 89
III LinkedList single linked list of Java data structure and algorithm
1. Overview of linked list
Linked list has the characteristics of continuous logic, discontinuous physical storage and variable size. It is realized based on pointer. Each node in the single linked list and one-way circular linked list contains one
A data field and a pointer field. The data field saves the data of the node, and the pointer field saves the position of the next node of the node. When it is necessary to find the next node of the current node, you can use the
The location information saved in the pointer field to locate the next node. The two-way circular linked list contains two pointer fields and one data field. The two pointers and respectively represent the position and of the previous node
The location of the next node.
2. Linked list classification is structure
(1) Single linked list
1.1 headless node single link list
1.2 single linked list with header node
(2) One way circular linked list
(3) Bidirectional circular linked list
3. Single linked list
3.1 functions (Methods) that need to be realized by user-defined single linked list
3.2 single linked list implementation code
(1) Custom linked list class customlinkedlist java
package com.datastructure.test; public class CustomLinkedList { //Single linked list data length private int size = 0; //struct Node private Node rootNode; //Linked list position subscript private int foot = 0; /* * Add node * Idea: construct the node class according to the incoming data to judge whether there is a root node. If it does not exist, set the new node as the root node. If it exists, add it to the back of the last node */ public boolean add(Object data) { if (data == null) { return false; } Node newNode = new Node(data); if (rootNode == null) { rootNode = newNode; }else { rootNode.addNode(newNode); } this.size ++; return true; } /* * Delete node * Idea: here, you need to consider whether the data exists in the linked list. If so, you can do the corresponding processing according to whether it is the root node */ public boolean remove(Object data){ if (!this.isExist(data)) { return false; }else { if (rootNode != null) { if (rootNode.data.equals(data)) { //Make the next node of the root node the root node rootNode = rootNode.nextNode; }else { rootNode.removeNode(data); } } size--; return true; } } /* * Get the corresponding data according to the index */ public Object get(int index){ if (index > this.size) { return null; } return this.rootNode.get(index); } /* * Return linked list length */ public int size(){ return this.size; } /* * Judge whether the linked list is empty */ public boolean isEmpty(){ return this.size == 0; } /* * The incoming data array is added to the linked list at one time */ public boolean addAll(Object data[]) { //Call the add method of Node in a loop to add data for (int i = 0; i < data.length; i++) { if (!this.add(data[i])) { return false; } } return true; } /* * Judge whether the specified data exists in the linked list */ public boolean isExist(Object data) { if (rootNode==null || data == null) { return false; } return this.rootNode.isExistNode(data); } /* * Clear linked list data */ public void clear(){ this.rootNode = null; this.size = 0; } /* * Output data of all nodes */ public void print(){ if (rootNode != null) { System.out.print(rootNode.data+" "); rootNode.printNode(); } } /** * Node The internal class is mainly used to form a linked list. It has done some auxiliary operations for the related operations of the linked list * At the same time, the function of implementing internal classes is to facilitate mutual access between internal classes and external classes * @author elimy * */ class Node { //Node data private Object data; //The node pointer field represents the next node private Node nextNode; /* * Incoming data construction method */ public Node(Object data){ this.data = data; } /* * Add nodes according to the incoming nodes */ public void addNode(Node newNode){ //Judge whether the next node of a node is empty. If it is empty, add a new node. If it is not empty, move another node down to continue to judge whether the next node of this node is empty if (this.nextNode == null) { this.nextNode = newNode; }else { this.nextNode.addNode(newNode); } } /* * Delete the existing node according to the value of the incoming node */ public void removeNode(Object dataVal){ //Judge that the next node of the current node is not empty if (this.nextNode != null) { //Judge whether the input data of the next node data field of the current node is equal. If they are equal, point the pointer field to the next node position of the next node to delete the node if (this.nextNode.data.equals(dataVal)) { this.nextNode = this.nextNode.nextNode; }else { this.nextNode.removeNode(dataVal); } } } /* * Judge whether it exists according to the incoming data. If it exists, return true and if not, return false */ public boolean isExistNode(Object dataVal){ //If the data field of the current node is equal to the incoming data, put it back to true directly if (this.data.equals(dataVal)) { return true; }else { //If the current node is not equal, judge whether the next node is null. If not, judge whether the next node of the current node is equal to the incoming value, and recursively cycle in turn if (this.nextNode !=null) { return this.nextNode.isExistNode(dataVal); }else { return false; } } } /* * Recursive loop printout node */ public void printNode(){ if (this.nextNode !=null) { System.out.print((this.nextNode.data).toString()+" "); this.nextNode.printNode(); } } /* * Return the corresponding data according to the incoming index */ public Object get(int index) { if (CustomLinkedList.this.foot++ == index) { return this.data; }else { return this.nextNode.get(index); } } } }
(2) Test class linklisttest java
package com.datastructure.test; public class LinklistTest { public static void main(String[] args) { CustomLinkedList linkedList = new CustomLinkedList(); linkedList.add("I"); linkedList.add("am"); linkedList.add("Andy"); System.out.println("Whether it is empty:"+linkedList.isEmpty()); System.out.println("am Is there:"+linkedList.isExist("am")); System.out.println("Element with index 0:"+(String)linkedList.get(0)); System.out.println("Linked list length:"+linkedList.size()); System.out.print("All elements of the linked list are:"); linkedList.print(); System.out.println(); //Delete I element linkedList.remove("I"); System.out.print("After deletion, all elements in the linked list are:"); linkedList.print(); } }
(3) Console printout:
Whether it is empty: false am Is there: true Element with index 0: I Linked list length: 3 All elements of the linked list are: I am Andy After deletion, all elements in the linked list are: am Andy
IV Queue queue of Java data structure and algorithm
1. Queue overview
Queue is a special linear table, which can be realized by array and linked list. The difference between queue and single linked list and array is that it can only add elements from the end of the queue,
The team leader deletes elements and meets the principle of first in first out (IFIO).
2. Queue classification
3. The array implements a custom queue
(1) Custom queue interface customqueue java
package com.datastructure.test; /* * The user-defined queue interface defines the methods to be implemented by the queue and provides them to the class inheritance implementation */ public interface CustomQueue<T> { //Queue function to add elements to the queue public void put(T data)throws Exception; //Queue out function to delete queue elements public T remove()throws Exception; //Determine whether the queue is empty public boolean isEmpty(); //Gets the length of the queue public int size(); //Get queue header element public T getFrontElement()throws Exception; }
(2) The array implements the custom class customarrayqueue java
package com.datastructure.test; public class CustomArrayQueue<T> implements CustomQueue<T> { //Default queue length static final int defaultSize = 15; //Queue element collection private T[] queueVals; //queue length private int size; //The location of the first object in the queue private int front; //The location of the current object in the queue private int rear; /* * Default construction method: set the default queue length to 15 */ @SuppressWarnings("unchecked") public CustomArrayQueue (){ front=rear=0; size = 0; queueVals = (T[]) new Object[defaultSize]; } /* * With parameter construction method, the queue length can be customized */ @SuppressWarnings("unchecked") public CustomArrayQueue (int defineSize){ front=rear=0; size = 0; queueVals = (T[]) new Object[defineSize]; } /* * Add object to queue */ @Override public void put(T data) throws Exception { if (size>0 && front==rear) { throw new Exception("The queue is full!"); }else { queueVals[rear] = data; rear =(rear+1)%(queueVals.length); size++; } } /* * First element from queue */ @Override public T remove() throws Exception { T object = null; if (isEmpty()) { throw new RuntimeException("There's nothing in the queue!"); }else { //Get team leader object element object = queueVals[front]; //Set the queue head element to null queueVals[front] = null; front =(front+1)%(queueVals.length); size--; } return object; } /* * Judge whether the queue is empty */ @Override public boolean isEmpty() { return size==0; } /* * Get queue length */ @Override public int size() { return size; } /* * Get queue header element */ @Override public T getFrontElement() throws Exception { if (isEmpty()) { throw new RuntimeException("There's nothing in the queue!"); }else { return queueVals[front]; } } }
(3) Test class
package com.datastructure.test; public class ArrayQueueTest { public static void main(String[] args) { CustomArrayQueue<String> queue = new CustomArrayQueue<String>(10); try { System.out.println("Is the queue empty:"+queue.isEmpty()); queue.put("A"); queue.put("B"); queue.put("C"); queue.put("D"); queue.put("E"); System.out.println("The first element of the team is:"+queue.getFrontElement()); System.out.println("Queue length:"+queue.size()); System.out.print("Remove element:"); while (!queue.isEmpty()) { System.out.print(queue.remove()+" "); } System.out.println(); System.out.println("Queue length:"+queue.size()); } catch (Exception e) { e.printStackTrace(); } } }
(4) Console printout
Is the queue empty:true The first element of the team is:A Queue length: 5 Remove element: A B C D E Queue length: 0
4. The linked list implements user-defined queues
(1) Custom queue interface (consistent with 3)
(2) Linked list custom queue class
package com.datastructure.test; public class CustomLinkedQueue<T> implements CustomQueue<T> { private Node front; private Node rear; private int size; public CustomLinkedQueue(){ //Set the beginning and end nodes to be empty during initialization front = rear =null; //The number of initialization nodes is 0 size = 0; } /* * Add new node to tail */ @Override public void put(T data) throws Exception { Node newNode = new Node(data, null); if (isEmpty()) { front = newNode; //Set the new node as the tail node rear = newNode; }else { //Add a new node after the tail node rear.nextNode = newNode; //Set the new node as the tail node rear = newNode; } size++; } /* * Remove team leader element */ @Override public T remove() throws Exception { T object = null; if (isEmpty()) { throw new RuntimeException("The queue is empty!"); }else { //Save the first element value object = front.data; //Set the next node as the team leader node front =front.nextNode; } size--; return object; } /* * Judge whether the queue is empty */ @Override public boolean isEmpty() { return size==0; } /* * Returns the length of the queue */ @Override public int size() { return size; } /* * Return the data of the first node of the queue */ @Override public T getFrontElement() throws Exception { return front.data; } /** * Node inner class */ class Node { T data; Node nextNode; /* * Head node construction method */ public Node(Node nextNode){ this.nextNode =nextNode; } /* * Other node construction methods */ public Node(T data,Node nextNode){ this.data=data; this.nextNode =nextNode; } } }
(3) Test class
package com.datastructure.test; public class LinkedQueueTest { public static void main(String[] args) { CustomLinkedQueue<String> queue = new CustomLinkedQueue<String>(); try { System.out.println("Is the queue empty:"+queue.isEmpty()); queue.put("A"); queue.put("B"); queue.put("C"); queue.put("D"); queue.put("E"); System.out.println("The first element of the team is:"+queue.getFrontElement()); System.out.println("Queue length:"+queue.size()); System.out.print("Remove element:"); while (!queue.isEmpty()) { System.out.print(queue.remove()+" "); } System.out.println(); System.out.println("Queue length:"+queue.size()); } catch (Exception e) { e.printStackTrace(); } } }
(4) Console printout
Is the queue empty:true The first element of the team is:A Queue length: 5 Remove element: A B C D E Queue length: 0
V Stack stack of Java data structure and algorithm
1. Stack overview
Stack, like queue, is also a kind of linear table. Its only feature is that it needs to meet the first in last out (FILO) rule, that is, it can only operate on one end of the stack and add data
It is called pressing stack, and removing data is called elastic stack. In java, the stack can be implemented in three ways: array, linked list and set (ArrayList / LinkedList).
2. Array implementation custom stack
(1) Custom stack interface customstack java
package com.datastructure.test; public interface CustomStack<T> { //Stack pressing method public void push(T data)throws Exception; //Pop up / remove the top element and return the corresponding data public T pop()throws Exception; //Gets the first element of the stage public T peek(); //Determine whether the stack is empty public boolean empty(); //Returns the number of elements in the stack public int size(); }
(2) Array custom stack class customarraystack java
package com.datastructure.test; public class CustomArrayStack<T> implements CustomStack<T> { static final int defaultSize = 15; //Indicates the location of the top element private int size; private T[] arrays; /* * No parameter construction method, do some initialization operations */ @SuppressWarnings("unchecked") public CustomArrayStack() { size = 0; arrays = (T[]) new Object[defaultSize]; } /* * Initialize the array according to the user-defined array size */ @SuppressWarnings("unchecked") public CustomArrayStack(int customSize) { size = 0; arrays = (T[]) new Object[customSize]; } /* * Add an element to the top of the stack */ @Override public void push(T data) throws Exception { if (size<arrays.length) { arrays[size] = data; size++; }else { throw new Exception("The array stack is full!"); } } /* * Remove the element at the top of the stack */ @Override public T pop() throws Exception { T topData; if (empty()) { throw new Exception("Array stack is empty!"); }else { topData = arrays[size-1]; size--; } return topData; } /* * Get the element at the top of the stack */ @Override public T peek() { return arrays[size-1]; } /* * Determine whether the stack is empty */ @Override public boolean empty() { return size==0; } /* * Returns the length of the stack */ @Override public int size() { return size; } }
(3) Test class customarraystacktest java
package com.datastructure.test; public class CustomArrayStackTest { public static void main(String[] args) { CustomArrayStack<String> stack = new CustomArrayStack<>(10); System.out.println("Is it empty:"+stack.empty()); try { stack.push("I"); stack.push("am"); stack.push("andy"); } catch (Exception e) { e.printStackTrace(); } System.out.println("Stack top element:"+stack.size()); System.out.println("Stack top element:"+stack.peek()); try { System.out.println("Removing Elements :"+stack.pop()); } catch (Exception e) { e.printStackTrace(); } System.out.println("Stack top element:"+stack.size()); System.out.println("Stack top element:"+stack.peek()); } }
(4) Test console output
Is it empty:true Stack length:3 Stack top element:andy Removing Elements :andy Stack length:2 Stack top element:am
3. Linked list implementation custom stack
(1) Custom stack interface customstack Java (consistent with 2)
(2) Linked list custom stack class customlinkedstack java
package com.datastructure.test; public class CustomLinkedStack<T> implements CustomStack<T> { private int size; private Node topNode; @Override public void push(T data) throws Exception { Node newTopNode; if (empty()) { newTopNode = new Node(data, null); }else { newTopNode = new Node(data, topNode); } topNode = newTopNode; size++; } @Override public T pop() throws Exception { Node oldTopNode = topNode; topNode = topNode.nextNode; size--; return oldTopNode.data; } @Override public T peek() { return topNode.data; } @Override public boolean empty() { return size==0; } @Override public int size() { return size; } /** * Node inner class */ class Node{ private T data; private Node nextNode; public Node(T data,Node nextNode){ this.data = data; this.nextNode = nextNode; } } }
(3) Test class customlinkedstacktest java
package com.datastructure.test; public class CustomLinkedStackTest { public static void main(String[] args) { CustomLinkedStack<String> stack = new CustomLinkedStack<>(); System.out.println("Is it empty:"+stack.empty()); try { stack.push("I"); stack.push("am"); stack.push("andy"); } catch (Exception e) { e.printStackTrace(); } System.out.println("Stack length:"+stack.size()); System.out.println("Stack top element:"+stack.peek()); try { System.out.println("Removing Elements :"+stack.pop()); } catch (Exception e) { e.printStackTrace(); } System.out.println("Stack length:"+stack.size()); System.out.println("Stack top element:"+stack.peek()); } }
(4) The test results are consistent with 2
4. Set implementation custom stack
(1) Custom stack interface customstack Java (consistent with 2)
(2) The collection class LinkedList implements custom collectionstack java
package com.datastructure.test; import java.util.LinkedList; class CustomCollectionStack<T> implements CustomStack<T> { private LinkedList<T> linkedList = new LinkedList<>(); public CustomCollectionStack() { } @Override public void push(T data) throws Exception { linkedList.add(data); } @Override public T pop() throws Exception { return linkedList.removeLast(); } @Override public T peek() { return linkedList.getLast(); } @Override public boolean empty() { return linkedList.isEmpty(); } @Override public int size() { return linkedList.size(); } }
(3) Test class customcollectionstacktest java
package com.datastructure.test; public class CustomCollectionStackTest { public static void main(String[] args) { CustomCollectionStack<String> stack = new CustomCollectionStack<>(); System.out.println("Is it empty:"+stack.empty()); try { stack.push("I"); stack.push("am"); stack.push("andy"); } catch (Exception e) { e.printStackTrace(); } System.out.println("Stack length:"+stack.size()); System.out.println("Stack top element:"+stack.peek()); try { System.out.println("Removing Elements :"+stack.pop()); } catch (Exception e) { e.printStackTrace(); } System.out.println("Stack length:"+stack.size()); System.out.println("Stack top element:"+stack.peek()); } }
(4) The results are consistent with 2
--------
Copyright notice: This article is the original article of CSDN blogger "rain in the alley", which follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link and this notice for reprint.
Original link: https://blog.csdn.net/qq_28057577/article/details/52712600