Java advanced -day02 linked list tree collection

Posted by php2MySQL on Sat, 30 Oct 2021 01:10:27 +0200

1. Linked list

A linked list is usually composed of a series of nodes. Each node contains any instance data and one or two links to the location of the previous or next node.

Linked list is a linear list, but it does not store data in linear order, but stores the pointer of the next node in each node.

1.1 classification

The node of a single linked list is divided into two parts. The first part saves the data of the node and the second part saves the address of the next node. The portion of the last node's storage address points to a null value.

Unidirectional linked list can only traverse in one direction. When finding a node, you need to start from one node and visit the next node every time until the required location

public class SingleLinkedList {
    // Number of nodes in the linked list
    private int size;
    //Head node
    private Node head;
    public  SingleLinkedList(){
        size = 0;a
        head= null;
    }
    // Node class of linked list
    private class Node{
        private Object data;//Data field of node
        private Node next;//Pointer to the next node
        public Node(Object data){
            this.data = data;
        }
    }
    // Add elements C - > b - > A to the linked list
    public Object addHead(Object data){
        Node newHead = new Node(data);// Create a new node
        if(size == 0 ){
            head = newHead;
        }else{
            newHead.next = head;//The pointer of the new node points to the original header node
            head = newHead;//The head node points to the new node
        }
        size++;
        return data;
    }
    // Delete node does not delete the node in the chain header
    public  Object deleteHead(){
        Object obj = head.data;
        head = head.next;
        size--;
        return obj;
    }
    //Find the specified element in the linked list, find the return Node node, and return null if it is not found
    public Node find(Object data){
        Node current = head;//Define a pointer to the node of the current comparison
        int tempSize = size;// Gets the number of elements in the current linked list
        while(tempSize > 0 ){
            if(data.equals(current.data)){
                return  current;
            }else{
                current = current.next;
            }
            tempSize--;
        }
        return  null;
    }
    // If the specified element is deleted successfully, return true; otherwise, return false
    public  boolean delete(Object data){
        if(size == 0 ){
            return  false;
        }
        // Get the previous node and its subsequent node of the deleted node
        Node current = head;
        Node previous = head;
        while(!current.data.equals(data)){
            if (current.next == null){// Judge whether to reach the end of the linked list
                return  false;
            }else{// The current node is not the node we want to delete and does not reach the end of the node
                previous = current;//Moves the pointer of the previous node
                current = current.next;//Move the pointer of the current node to the next node
            }
        }
        // This indicates that the node to be deleted has been found. Judge whether the deleted node is the head node
        if(current == head){
            head = current.next;
            size--;
        }else{//Not a header node
            previous.next =current.next;
            size--;
        }
        return  true;
    }
    // Judge whether the node is empty
    public  boolean isEmpty(){
        return  size==0;
    }
    // Traversal linked list
    public  void  display(){
        if(size > 0 ){
            Node node = head;
            int tempSize = size;
            if(tempSize == 1){// If the current linked list has only one header node
                System.out.println("[" + node.data+"]");
                return;
            }
            while(tempSize >0 ){
                if(node.equals(head)){
                    System.out.print("[" + node.data+"->");
                }else if(node.next == null){
                    System.out.print( node.data+"]");
                }else{
                    System.out.print(node.data+"->");
                }
                node= node.next;
                tempSize--;
            }
            System.out.println();
        }else{// The linked list has no nodes
            System.out.println("[]");
        }
    }
}

test

public class SingleLinkListTest {
    public static void main(String[] args) {
        SingleLinkedList sls = new SingleLinkedList();
        sls.addHead("A");
        sls.addHead("B");
        sls.addHead("C");
        sls.addHead("D");
        sls.display();
        //Test delete element delete C
        sls.delete("C");
        sls.display();
        //Find B
        System.out.println(sls.find("C"));
    }
}

1.2 differences between stack queue linked lists

The stack queue is a linear table with limited operation.

The difference is that the operation rules are different

Linked lists and arrays:

1 occupied memory space the memory space stored in the linked list can be continuous or discontinuous. The array must be continuous.

2 length variability the length of the linked list can be customized according to actual needs. Once the array length is defined, it cannot be changed.

3. Data access: linked list access requires mobile access, which is more convenient than array access

4 usage scenario: the element array is more suitable for large amount of data and frequent access

Delete, insert and other operations are more suitable for linked lists

Features of linked list:

Logical structure one to one

Storage result sequence table chain table

Operation rules: stored in random order

Stack:

Logical structure one to one

Store result sequence stack

Operation rules: last in, first out, first in, last out

queue

Logical structure one to one

Storage result sequence queue

Operation rules: first in first out

Bidirectional linked list

Circular linked list:

2. Nonlinear structure (tree structure)

2.1 binary tree

Each element is called a node

A root node

B C D parent node

Leaf node: node without child nodes (H E F G)

Height of tree: maximum number of layers

subtree

The forest is made up of several sub trees

A tree in which each node has at most two child nodes is called a binary tree

If the leaf nodes of all binary trees are at the last time. The number of nodes = 2^n - 1 n is the number of layers. Such a binary tree is called a full binary tree

2.2 traversal of binary tree

Preorder traversal: first output the parent node, and then traverse the left and right subtrees

Medium order traversal: first traverse the left subtree, then the output parent node, and finally traverse the right subtree

Post order traversal: first traverse the left subtree, then the right subtree, and finally output the parent node

Sequence traversal: traverse layer by layer according to the level

2.3 red black tree

Red black tree is a kind of binary tree with red black nodes and can be self balanced. He must satisfy the following properties:

1 each node is either black or red

2. The root node is black

3 each leaf node is NIL and black

4 the two child nodes of each red node must be black

The path from any node to the leaf node contains the same number of black nodes

3 set

public class Student {
    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

public class StudentTest {
    public static void main(String[] args) {
        Student stu1 = new Student("Zhang San",18);
        Student stu2 = new Student("Li Si",21);
        Student stu3 = new Student("Wang Wu",20);
        Student stu4 = new Student("Zhao Liu",22);
        Student[] stus = new Student[5];// Create an array of custom types
        stus[0] = stu1;
        stus[1] = stu2;
        stus[2] = stu3;
        stus[3] = stu4;
        for(Student student :stus){
            System.out.println(student);
        }
    }
}

In the above code, the array is used to store multiple objects, but the array itself has some inevitable disadvantages. java provides a new structure for storing objects. This structure is a collection. The collection is like a container, which can dynamically put the references of multiple objects into the container.

Characteristics of array in memory storage:

1 the length of the array is determined after initialization and cannot be changed

2 the type of array declaration determines the type of element initialization

Disadvantages of array in storage:

1. After the output is initialized, the length is not variable and it is not easy to expand

2 there are few attributes and methods provided in the array, which is not convenient for adding, deleting, inserting and other operations on elements, and the efficiency is not high. At the same time, the number of stored elements cannot be obtained directly.

3 the data stored in the array is orderly and can be repeated.

java collections can store multiple objects in varying numbers, and can also store data with mapping relationships.

3.1 architecture of collection

Collection features: provide a storage model with variable storage space, and the capacity of stored data can be changed at any time.

  • public interface Collection<E>  extends Iterable<E>
    

    The root interface in the collection hierarchy can only store objects, but other collections are not allowed. Some sets are ordered, while others are disordered. The JDK does not provide any direct implementation of this interface: it provides more specific implementations of sub interfaces, such as Set and List. This interface is typically used to pass collections and operate on them when maximum versatility is required. (polymorphism)

3.2 use of collection interface

Collection is the top-level interface of a single column collection. It represents a set of objects, which are also called elements.

The JDK does not provide a direct implementation of this interface, but you can create collection objects through the implementation of sub interfaces

    • booleanAdd (E) ensures that the collection contains the specified element (optional operation).
      booleanAddall (collection <? Extensions E > C) adds all elements in the specified collection to this collection (optional).
      voidclear() removes all elements from this collection (optional).
      booleancontains(Object o) returns true if the collection contains the specified element.
      booleanContainsall (collection <? > C) returns true if the collection contains all elements in the specified collection.
      booleanequals(Object o) compares the specified object to this collection for equality.
      inthashCode() returns the hash code value of this collection.
      booleanisEmpty() returns true if this collection does not contain elements.
      Iterator<E>iterator() returns an iterator for the elements in this collection.
      booleanremove(Object o) removes a single instance (if any) of the specified element from the collection (optional).
      booleanRemoveAll (collection <? > C) deletes all elements of this collection contained in the specified collection (optional).
      booleanRetain all (collection <? > C) only the elements contained in the specified collection in this collection are retained (optional operation).
      intsize() returns the number of elements in this collection.
      Object[]toArray() returns an array containing all the elements in this collection.
      <T> T[]toArray(T[] a) returns an array containing all elements in this collection; The runtime type of the returned array is the runtime type of the specified array.
    public static void main(String[] args) {
        //Create a Collection object
        Collection collection = new ArrayList();
        //Adding elements to methods in the Collection interface
        collection.add("Hello");
        collection.add(123);//Packing class of basic type corresponding to automatic packing
        collection.add(true);
        System.out.println(collection);
    }
    public static void main(String[] args) {
        //Create a Collection object
        Collection collection = new ArrayList();
        //Adding elements to methods in the Collection interface
        collection.add("Hello");
        collection.add(123);//Packing class of basic type corresponding to automatic packing
        collection.add(true);
       // collection.clear();// Clear elements in collection
        // Determine whether the collection contains an object
        System.out.println(collection.contains(123));
        // Remove an element from the collection
        System.out.println(collection.remove(123));
        // Determine whether the collection is empty
        System.out.println(collection.isEmpty());
        //Gets the number of elements in the collection
        System.out.println(collection.size());
        //Convert a collection to an array
        Object[] arr = collection.toArray();
        System.out.println(arr.length);
        System.out.println(collection);
    }
public class CollectionTest {    public static void main(String[] args) {        //Create a collection object collection collection = new arraylist()// Add the element collection. Add ("hello") to the method in the collection interface; collection.add(123);// The packing class collection.add (true) of the basic type corresponding to automatic packing; Collection c1 = new ArrayList();         c1.add("world");         c1.add("hello");         c1.add(false);         Student stu1 = new student ("Zhang San", 18); c1.add(stu1);        //  addAll        collection.addAll(c1);         System.out.println(collection);        // Judge whether the set contains all elements in another set, System.out.println(collection.containsAll(c1))// Take the intersection of two sets and store it in the current collection. RetainAll (C1); System.out.println(collection);        // Delete another collection in this collection / / collection.removeall (C1)// System.out.println(collection);    }

3.2.1. Iterator

Iterator for iterated sets

    • booleanhasNext() returns true if the iteration has more elements.
      Enext() returns the next element in the iteration.
    public static void main(String[] args) {        //Create a Collection object Collection collection = new arraylist()// Add the element Collection. Add ("hello") to the method in the Collection interface; Collection.add(123);// The packing class Collection.add (true) of the basic type corresponding to automatic packing; Collection.add("world");         Collection.add("hello");         Collection.add(false);         Student stu1 = new student ("Zhang San", 18); Collection.add(stu1);        //  Iterator iterator = Collection. Iterator()// Iterator is used to iterate the Collection while (ITER. Hasnext()) {object obj = ITER. Next(); system. Out. Println (obj);}}

Source code analysis

ArrayList

   public boolean hasNext() {            return cursor != size;// Size indicates the number of elements in the collection} @ suppresswarnings ("unchecked") public e next() {checkforconfirmation(); int i = cursor; if (I > = size) throw new nosuchelementexception(); object [] elementdata = arraylist.this.elementdata; if (I > = elementdata. Length)                 throw new ConcurrentModificationException();            cursor = i + 1;            return (E) elementData[lastRet = i];        }

3.3 List

3.3.1 characteristics of list set

  • Ordered sets (also known as sequences). You can precisely control the insertion position of each element in the list. Users can access elements through integer indexes (positions in the list) and search for elements in the list.

  • Lists usually allow duplicate elements

  • null can be stored and multiple can be stored

    Typical implementation

    ArrayList LinkedList Vector

    3.3.2 List interface specific methods

      • add(int index, Object element) inserts the specified element into the specified position in this list (optional operation).
      • Objectget(int index) returns the element at the specified position in this list.
      • intindexOf(Object o) returns the index of the first occurrence of the specified element in the list. If the list does not contain an element, it returns - 1.
    • intlastIndexOf(Object o) returns the index of the last occurrence of the specified element in the list. If the list does not contain an element, it returns - 1.
    • ListIterator<E>listIterator() returns the list iterators in the list (in the appropriate order).
    • Eset(int index, E element) replaces the element at the specified position in this list with the specified element (optional operation).
    • List<E>subList(int fromIndex, int toIndex) returns the view between fromIndex (inclusive) and toIndex specified in this list.

3.3.3. Use of list

public class ListTest {    public static void main(String[] args) {        Student stu1 = new Student("Zhang San",18);        Student stu2 = new Student("Li Si",21);        Student stu3 = new Student("Wang Wu",20);        Student stu4 = new Student("Zhao Liu",22);        List list = new ArrayList();        list.add(stu4);        list.add(stu3);        list.add(stu2);        list.add(stu1);        list.add(stu1);        list.add(stu2);        list.add(stu3);        list.add(stu4);       Iterator iter =  list.iterator();       while(iter.hasNext()){           Object obj = iter.next();           System.out.println(obj);       }        System.out.println("------------------------------");       for(int i = 0 ; i < list.size();i++){            Object obj = list.get(i);           System.out.println(obj);       }    }}

Order of List set: the order here means that the storage order of elements is consistent with the iterative order

Iterative method of set

   public static void main(String[] args) {        Student stu1 = new Student("Zhang San",18);        Student stu2 = new Student("Li Si",21);        Student stu3 = new Student("Wang Wu",20);        Student stu4 = new Student("Zhao Liu",22);        List list = new ArrayList();        list.add(stu4);        list.add(stu3);        list.add(stu2);        list.add(stu1);        list.add(stu1);        list.add(stu2);        list.add(stu3);        list.add(stu4);       Iterator iter =  list.iterator();       while(iter.hasNext()){           Object obj = iter.next();           System.out.println(obj);       }        System.out.println("------------------------------");       for(int i = 0 ; i < list.size();i++){            Object obj = list.get(i);           System.out.println(obj);       }        System.out.println("------------------------------");       for(Object obj : list){           System.out.println(obj);       }        System.out.println("------------------------------");       for(  Iterator itr =  list.iterator();itr.hasNext();){           Object obj = itr.next();//When iterating with iterators, the next method can only call System.out.println(obj) at one place in a loop;} System.out.println("------------------------------");         Iterator itr1 =  list.iterator();         For (; itr1. Hasnext();) {object obj = itr1. Next(); / / when iterating with iterators, the next method can only call System.out.println(obj);}}

Iterators use while and for, which is better:

The for loop is more conducive to the release of space

However, while is widely used in development

3.3.4 concurrent modification exception

    public static void main(String[] args) {        List list = new ArrayList();        list.add("hello");        list.add("world");        list.add("java");        Iterator iter =  list.iterator();        while(iter.hasNext()){            Object obj = iter.next();            String str = (String) obj;            if(str.equals("world")){                list.add("hadoop");            }        }    }

Concurrent modificationexception: concurrent modification exception

Causes:

In the process of iterating the set, the iterator modifies the elements of the set through the set object, resulting in the inconsistency between the expected modified value and the actual modified value judged by the iterator in the acquisition garden

Solution: traverse the set through the set itself, and modify the set itself

for(int i = 0 ; i < list.size();i++){    String str = (String)list.get(i);    if(str.equals("world")){      //  list.add("hadoop");// Add to the end of the set list.set(i,"hadoop")// Modify the element}} System.out.println(list);

3.3.5 ListIteator

    • voidAdd (E) inserts the specified element into the list (optional).
      booleanhasNext() returns true. If you traverse the forward list, the list iterator has multiple elements.
      booleanhasPrevious() returns true. If you traverse the reverse list, the list iterator has multiple elements.
      Enext() returns the next element in the list and advances the cursor position.
      intnextIndex() returns the subsequent call. next() The index of the element returned.
      Eprevious() returns the previous element in the list and moves the cursor position backward.
      intpreviousIndex() is returned by subsequent calls previous() The index of the element returned.
      voidremove() removes from the list next() or previous() The last element returned (optional operation).
      voidFor set (E) designated Element replacement by next() or previous() The last element returned (optional operation).
public class ListDemo {    public static void main(String[] args) {        List list = new ArrayList();        list.add("hello");        list.add("world");        list.add("java");        // Get list iterator listiterator = list. Listiterator()// While traversing Tianjian while (iterator. Hasnext()) {object obj = iterator. Next(); / / when the element is world, add the element spring if (obj. Equals ("world")) {iterator. Add ("spring"); iterator. Previous(); / / Yes, the pointer points to the previous element}             System.out.println(obj);        }        System.out.println(list);        System.out.println("-----------------------");        // Delete the element listiterator while iterating. Iterator1 = list. Listiterator(); while(iterator1.hasNext()){            Object obj = iterator1.next();            if(obj.equals("world")){                iterator1.remove();            }else{                System.out.println(obj);            }        }        System.out.println("-----------------------");        // Modify listiterator iterator2 = list. Listiterator(); while(iterator2.hasNext()){            Object obj = iterator2.next();            if(obj.equals("hello")){                iterator2.set("mybatis");                iterator2.previous();            }else{                System.out.println(obj);            }        }    }}
    public static void main(String[] args) {        List list = new ArrayList();        list.add("hello");        list.add("world");        list.add("java");        ListIterator iter = list.listIterator();        while(iter.hasNext()){            Object obj = iter.next();            System.out.println(obj);        }        System.out.println("----------------------");//Before reverse order, you must traverse while (ITER. Hasprevious()) {object obj = ITER. Previous(); system. Out. Println (obj);}}
       List sub =  list.subList(1,2);//The obtained subset contains 1 and does not contain 2 system.out.println (sub);

Topics: Java data structure linked list