Data structure and algorithm Series IV (single chain table)

Posted by MagicMikey on Tue, 25 Feb 2020 06:32:34 +0100

1. introduction

1.1. Why study data structure and algorithm?

Some people say that data structure and algorithm, computer network, and operating system are the same, away from daily development, except for the interview may not be used in this life!

Some people say that I do business development. As long as I am proficient in API, framework and middleware, can not the code I write fly?

So the question comes: Why study data structure and algorithm?

 

#Reason 1:
	When interviewing, don't be held back by data structure and algorithm
#Reason 2:
	Do you really want to be CRUD Boy all your life
#Reason 3:
	Engineers who don't want to write open source framework and middleware are not good cooks

1.2. How to systematically learn data structure and algorithm?

I think it's better to learn data structure and algorithm. But I have two puzzles:

1. How to start learning?

2. What is there to learn?

Recommended learning methods:

#Learning methods
1. Starting from the foundation, systematic learning
2. More hands-on, each data structure and algorithm is implemented by code
3. Thinking is more important: understand the implementation idea and don't recite the code
4. Combined with daily development, corresponding application scenarios

Learning content recommendation:

There are many data structures and algorithms. Based on the practical principle, we learn classic and common data structures and algorithms

#Learning content:
1. Definition of data structure
2. Definition of algorithm
3. Complexity analysis
4. Common data structure
	Array, linked list, stack, queue
	Hash table, binary tree, heap
	Skip tables and graphs
5. Common algorithms
	Recursion, sorting, binary search
	Search, hash, greed, divide and conquer
	Dynamic planning, string matching

2. test you.

In the previous [data structure and algorithm Series III (array)], we know the most basic data structure: array. In this article, let's look at another basic data structure: linked list. The commonly used chain lists are: single chain list, double chain list and circular chain list.

This article we mainly look at: single chain table

#Test you:
1. Can you describe the list in your own words?
2. Do you know the difference between linked list and array?
3. Do you know any common linked lists?

3. cases

3.1. Definition of linked list

Like array, linked list is a common basic data structure, which uses a group of scattered memory blocks in series through "pointer". Each fragmented block of memory is called a node.

In order to concatenate all nodes, each link node needs to store not only the data, but also the address of the next node on the chain. We call the pointer to store the address of the next node as follow pointer.

The linked list has two special nodes: the head node and the tail node

Head node: first node

Tail node: subsequent pointer to null node

As shown in the picture:

3.2. Difference between linked list and array

3.2.1. Memory space

We know one of the characteristics of arrays in the last article: they need continuous memory space. Linked list is just the opposite of array. Linked list does not need continuous memory space. It uses a group of scattered memory blocks in series through "pointer".

As shown in the picture:

3.2.2. Operation: insert and delete

To insert or delete an array, you need to move data backward or forward. The time complexity is: O(n)

To insert or delete a linked list, you only need to change the node pointer without moving the data. The time complexity is: O(1)

As shown in the picture:

3.2.3. Operation: Search

The memory space of the array is continuous, which supports random access. According to the index of subscript, the time complexity is: O(1)

The memory space of the linked list is not continuous, random access operation is not supported, and the access is traversed from the beginning node. The time complexity is: O(n)

3.3. Single chain table code implementation

3.3.1. Node encapsulation

/**
     * Link list node: node < E >
     */
    class Node<E>{
        private E e;
        private Node<E> next;

        public E getE() {
            return e;
        }

        public void setE(E e) {
            this.e = e;
        }

        public Node<E> getNext() {
            return next;
        }

        public void setNext(Node<E> next) {
            this.next = next;
        }
    }

3.3.2. Complete code

package com.anan.struct.linetable;

/**
 * Single chain table implementation ideas:
 *     1.A free head node, that is, the head node does not store data
 *     2.This is helpful to simplify the realization of linked list
 */
public class SingleLinkedList<E> {

    // Linked list size
    private int size;

    public int getSize() {
        return size;
    }

    // Chain header node
    private Node<E> head;
    // Chain tail node
    private Node<E> tail;

    public SingleLinkedList(){
        head = new Node<E>();
        tail = head;

        size = 1;
    }

    /**
     * Insert element at end of list
     */
    public boolean add(E e){
        // Create node
        Node<E> node = new Node<E>();
        node.setE(e);

        // Change tail node pointer to new node
        tail.next = node;
        // Set up a new tail node
        tail = node;

        // Chain size plus 1
        size ++;
        
        return true;
    }

    /**
     * Inserts a node at the specified index location
     */
    public boolean insertPos(int pos,E e){

       // Judge the validity of index location
        if(pos < 1 || pos > size ){
            return  false;
        }

        // Create node
        Node<E> node = new Node<E>();
        node.setE(e);

        // Get insertion location node
        Node<E> posNode = get(pos - 1);
        
        // Change the node pointer
        node.next = posNode.next;
        posNode.next = node;

        // Chain size plus 1
        size ++;
        
        return true;
    }

    /**
     * Delete link end element
     */
    public boolean remove(){

        // Get the penultimate element of the list
        Node<E> node = get(getSize() - 2);
        
        // Change tail node
        tail = node;
        node.next = null;

        // Chain list size minus 1
        size -- ;
        
        return true;
    }

    /**
     * Delete element at specified location (cannot delete header node)
     */
    public boolean delPos(int pos){

        // Judge the validity of index location
        if(pos < 1 || pos > size){
            return false;
        }

        // If you delete the last element
        if((pos + 1) == size){
            remove();
        }else{
            // Get delete element node
            Node<E> node = get(pos);
            // Get the previous node of the deleted element
            Node<E> preNode = get(pos - 1);

            // Delete operation
            preNode.next = node.next;

            // Chain list size minus 1
            size --;
        }

        return true;
    }


    /**
     * Gets the linked list node of the specified index
     */
    public Node<E> get(int index){
        // Judge index validity
        if(index < 0 || index > size - 1){
            return null;
        }

        // Traverse from the beginning of the node
        Node<E> node = head;
        for(int i=0; i< index; i++){
            node = node.next;
        }

        return node;
    }

    /**
     * Get data for the specified index location
     */
    public E getValue(int index){
        // Get node
        Node<E> node = get(index);
        if(node == null){
            return  null;
        }

        return  node.e;
    }

    /**
     * Link list node: node < E >
     */
    class Node<E>{
        private E e;
        private Node<E> next;

        public E getE() {
            return e;
        }

        public void setE(E e) {
            this.e = e;
        }

        public Node<E> getNext() {
            return next;
        }

        public void setNext(Node<E> next) {
            this.next = next;
        }
    }
}

3.3.3. test

package com.anan.struct.linetable;

/**
 * Test single chain table
 */
public class SingleLinkedListTest {

    public static void main(String[] args) {
        // 1. Create a linked list and add elements
        SingleLinkedList<Integer> list = new SingleLinkedList<Integer>();
        for (int i = 0; i < 5; i++) {
            list.add(i);
        }

        System.out.println("1.Create linked list,Additive elements-----------------------------------------");
        list(list);


        // 2. Insert element at specified location
        System.out.println("2.Insert element at specified position [5]-----------------------------------------");
        list.insertPos(5,666);
        list(list);


        // 3. Delete the end element of the linked list
        System.out.println("3.Delete end of linked list element-----------------------------------------");
        list.remove();
        list(list);


        // 4. Add elements at the end of the list again
        System.out.println("4.Add elements at the end of the list again-----------------------------------------");
        list.add(888);
        list(list);

        // 5. Delete the specified location element
        System.out.println("5.Delete the specified location [1] element-----------------------------------------");
        list.delPos(1);
        list(list);

    }

    /**
     * Traverse output list
     * @param list
     */
    public static  void list(SingleLinkedList<Integer> list){
        System.out.println("Current list size, size: " + list.getSize());
        for (int i = 1; i < list.getSize(); i++) {
            System.out.println(list.getValue(i));
        }
    }
}

Test results:

D:\02teach\01soft\jdk8\bin\java com.anan.struct.linetable.SingleLinkedListTest
1. Create a linked list and add elements-----------------------------------------
Current linked list size, size: 6
0
1
2
3
4
2. Insert element at specified position [5]-----------------------------------------
Current linked list size, size: 7
0
1
2
3
666
4
3. Delete the end element of the linked list-----------------------------------------
Current linked list size, size: 6
0
1
2
3
666
4. Add elements at the end of the list again-----------------------------------------
Current linked list size, size: 7
0
1
2
3
666
888
5. Delete the specified location [1] element-----------------------------------------
Current linked list size, size: 6
1
2
3
666
888

Process finished with exit code 0

4. Discussion and sharing

#Test your answer:
1. Can you describe the list in your own words?
  1.1. Linked list and array are common basic data structures
  1.2. Linked list uses a group of scattered memory blocks in series through "pointer"
  1.3. Each fragmented memory block is called a node
  1.4. Each node of the linked list needs to store a pointer to the next node in addition to storing data
  1.5. Generally, we call the pointer to the next node: subsequent pointer
  
2. Do you know the difference between linked list and array?
  2.1. The array needs continuous memory space, and the linked list does not
  2.2. Insert and delete
    2.2.1. The array needs to move data. The time complexity is: O(n)
    2.2.2. The linked list does not need to move data. The time complexity is: O(1)
    
  2.3. Search operation
    2.3.1. Array supports random access operation, with time complexity of O(1)
    2.3.2. The linked list needs to be traversed from the beginning node, and does not support random access operation. The time complexity is: O(n)

3. Do you know any common linked lists?
  3.1. Single chain table
  3.2. Two way list
  3.3. Circular list

Topics: network Java