Java data structure and algorithm_ Linear table_ Sequential list and linked list

Posted by mmitdnn on Fri, 21 Jan 2022 05:27:02 +0100


Linear table

summary

  • Linear table is the most basic, simplest and most commonly used data structure.
  • A linear table is a finite sequence of n data elements with the same characteristics.

Pioneer element: if element A is in front of element B, it is called the precursor element of B
Successor element: if element B is after element a, it is called the successor element of A
Characteristics of linear table: there is a "one-to-one" logical relationship between data elements.

  • The first data element has no precursor, and this data element is called a header node;
  • The last data element has no successor, and this data element is called the tail node;
  • In addition to the first and last data elements, other data elements have and have only one precursor and one successor

Classification of linear tables:
The data in the linear table can be stored in sequence or chain. According to different data storage methods, the linear table can be divided into sequence
Lists and linked lists.

Sequence table

summary:

  • Sequential table is a linear table saved in the form of array in computer memory
  • Sequential storage of linear table refers to the sequential storage of each element in the linear table with a group of storage units with continuous addresses, so that the data elements that ring logically in the linear table are stored in adjacent physical storage units
  • That is, the logical adjacency relationship between data elements is reflected through the adjacency relationship physically stored by data elements.

Sequence table API design

Sequence table class name SequenceList:

  • Construction method: SequenceList(int capacity): create a SequenceList object with capacity
  • Member variables:
    1.private T[] eles: array of storage elements
    2.private int N: length of current linear table
  • Member method
    1.public void clear(): empty linear table
    2.publicboolean isEmpty(): judge whether the linear table is empty, return true if yes, and return false if No
    3.public int length(): get the number of elements in the linear table
    4.public T get(int i): read and return the value of the ith element in the linear table
    5. Public void insert (int i, t, t): insert a data element with a value of T before the ith element of the linear table.
    6. Public void insert (T): add an element t to the linear table
    7.public T remove(int i): delete and return the ith data element in the linear table.
    8. Public int indexof (T): returns the bit sequence number of the specified data element that appears for the first time in the linear table. If it does not exist, it returns
    Return - 1

Code implementation of sequence table

import java.util.Iterator;

public class SequenceList<T> implements Iterable<T>{
    //An array of storage elements
    private T[] eles;
    //Record the number of elements in the current sequence table
    private int N;

    //Construction method
    public SequenceList(int capacity){
        //Initialize array
        this.eles=(T[])new Object[capacity];
        //Initialization length
        this.N=0;
    }

    //Set a linear table as an empty table
    public void clear(){
        this.N=0;
    }

    //Judge whether the current linear table is empty
    public boolean isEmpty(){
       return N==0;
    }

    //Gets the length of the linear table
    public int length(){
        return N;
    }

    //Gets the element at the specified location
    public T get(int i){
        return eles[i];
    }

    //Adds an element t to the linetype table
    public void insert(T t){
        if (N==eles.length){
            resize(2*eles.length);
        }

        eles[N++]=t;
    }

    //Insert element t at element i
    public void insert(int i,T t){
        if (N==eles.length){
            resize(2*eles.length);
        }

        //First, move the element at the i index and its subsequent elements backward by one bit
        for(int index=N;index>i;index--){
            eles[index]=eles[index-1];
        }
        //Then put the t element at the i index
        eles[i]=t;

        //Number of elements + 1
        N++;
    }

    //Delete the element at the specified position i and return it
    public T remove(int i){
        //Record the value at index i
        T current = eles[i];
        //The elements behind index i can be moved forward one bit in turn
        for(int index=i;index<N-1;index++){
            eles[index]=eles[index+1];
        }
        //Number of elements - 1
        N--;

        if (N<eles.length/4){
            resize(eles.length/2);
        }

        return current;
    }


    //Find where the t element first appears
    public int indexOf(T t){
        for(int i=0;i<N;i++){
            if (eles[i].equals(t)){
                return i;
            }
        }
        return -1;
    }

    //Reset the size of eles according to the parameter newSize
    public void resize(int newSize){
        //Define a temporary array that points to the original array
        T[] temp=eles;
        //Create a new array
        eles=(T[])new Object[newSize];
        //Copy the data of the original array to the new array
        for(int i=0;i<N;i++){
            eles[i]=temp[i];
        }
    }


    @Override
    public Iterator<T> iterator() {
        return new SIterator();
    }

    private class SIterator implements Iterator{
        private int cusor;
        public SIterator(){
            this.cusor=0;
        }
        @Override
        public boolean hasNext() {
            return cusor<N;
        }

        @Override
        public Object next() {
            return eles[cusor++];
        }
    }
}
//Test link
public class SequenceListTest {

    public static void main(String[] args) {
        //Create sequence table object
        SequenceList<String> sl = new SequenceList<>(10);
        //Test insertion
        sl.insert("Wang Xianzhi");
        sl.insert("Jian Jiuhuang");
        sl.insert("Li Chungang");
        sl.insert(1,"Xu Fengnian");

        for (String s : sl) {
            System.out.println(s);
        }
    //Test acquisition
        String getResult = sl.get(1);
        System.out.println("The result at index 1 is:"+getResult);
        //Test delete
        String removeResult = sl.remove(0);
        System.out.println("The deleted elements are:"+removeResult);
        //Test empty
        sl.clear();
        System.out.println("The number of elements in the cleared linear table is:"+sl.length());
    }
}


Linked list

summary:

  • Linked list is a non continuous and non sequential storage structure on the physical storage unit. Its physical structure can not only represent the logical order of data elements. The logical order of data elements is realized through the pointer link order in the linked list
  • The linked list consists of a series of nodes (each element in the linked list is called a node), which can be generated dynamically at run time.

Node API design

Class nameNode
Construction methodNode(T t,Node next):
Create Node object
Member variableT item: store data
Node next: points to the next node

Implementation node class

public class Node<T> { 
//Storage element 
	public T item; 
//Point to the next node 
	public Node next; 
	public Node(T item, Node next) {
		this.item = item;
		this.next = next; 
	 } 
}

Generate linked list:

public static void main(String[] args) throws Exception { 
	//Build node 
	Node<Integer> first = new Node<Integer>(11, null); 
	Node<Integer> second = new Node<Integer>(13, null); 
	Node<Integer> third = new Node<Integer>(12, null); 
	Node<Integer> fourth = new Node<Integer>(8, null); 
	Node<Integer> fifth = new Node<Integer>(9, null); 
	//Generate linked list 
	first.next = second; s
	econd.next = third; 
	third.next = fourth; 
	fourth.next = fifth; 
}

Unidirectional linked list

summary:

  • Unidirectional linked list is a kind of linked list. It is composed of multiple nodes. Each node is composed of a data field and a pointer field. The data field is used to store data and the pointer field is used to point to its subsequent nodes.
  • The data field of the head node of the linked list does not store data, and the pointer field points to the first node that really stores data.

One way linked list LinkList class:

  • Construction method: LinkList(): create a LinkList object
  • Member method:
    1.public void clear(): empty linear table
    2.publicboolean isEmpty(): judge whether the linear table is empty, return true if yes, and return false if No
    3.public int length(): get the number of elements in the linear table
    4.public T get(int i): read and return the value of the ith element in the linear table
    5. Public void insert (T): add an element to the linear table;
    6. Public void insert (int i, t, t): insert a data element with a value of T before the ith element of the linear table.
    7.public T remove(int i): delete and return the ith data element in the linear table.
    8. Public int indexof (T): returns the bit sequence number of the specified data element that appears for the first time in the linear table. If it does not exist, then
    Returns - 1.
  • Member internal class: private class Node: node class
  • Member variables:
    1.private Node head: record the first node
    2.private int N: record the length of the linked list
    Code demonstration of one-way linked list
import java.util.Iterator;
public class LinkList<T> implements Iterable<T>{
    //Record header node
    private Node head;
    //Record the length of the linked list
    private int N;



    //Node class
    private class Node {
        //Store data
        T item;
        //Next node
        Node next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }

    public LinkList() {
        //Initialize header node
        this.head = new Node(null,null);
        //Number of initialization elements
        this.N=0;
    }

    //Empty linked list
    public void clear() {
        head.next=null;
        this.N=0;
    }

    //Get the length of the linked list
    public int length() {
        return N;
    }

    //Determine whether the linked list is empty
    public boolean isEmpty() {
        return N==0;
    }

    //Gets the element at the specified location i
    public T get(int i) {

        //Through the loop, start from the node and look back, i times in turn, you can find the corresponding element
        Node n = head.next;
        for(int index=0;index<i;index++){
            n=n.next;
        }

        return n.item;
    }

    //Add element t to linked list
    public void insert(T t) {
        //Find the last current node

        Node n = head;
        while(n.next!=null){
            n=n.next;
        }


        //Create a new node and save the element t
        Node newNode = new Node(t, null);
        //Make the current last node point to the new node
        n.next=newNode;
        //Number of elements + 1
        N++;
    }

    //To the specified position i, add the element t
    public void insert(int i, T t) {
        //Find the previous node at position i
        Node pre = head;
        for(int index=0;index<=i-1;index++){
            pre=pre.next;
        }

        //Find the node at position i
        Node curr = pre.next;
        //Create a new node, and the new node needs to point to the node at the original i location
        Node newNode = new Node(t, curr);
        //The previous node in the original i position can point to the new node
        pre.next=newNode;
        //Number of elements + 1
        N++;
    }

    //Deletes the element at the specified position i and returns the deleted element
    public T remove(int i) {
        //Find the previous node at i location
        Node pre = head;
        for(int index=0;index<=i-1;i++){
            pre=pre.next;
        }
        //To find the node at i position
        Node curr = pre.next;
        //Find the next node at position i
        Node nextNode = curr.next;
        //The previous node points to the next node
        pre.next=nextNode;
        //Number of elements - 1
        N--;
        return curr.item;
    }

    //Find the position where the element t first appears in the linked list
    public int indexOf(T t) {
        //From the beginning, find each node in turn, take out the item, and compare it with t. If it is the same, it will be found
        Node n = head;
        for(int i=0;n.next!=null;i++){
            n=n.next;
            if (n.item.equals(t)){
                return i;
            }
        }
        return -1;
    }


    @Override
    public Iterator<T> iterator() {
        return new LIterator();
    }

    private class LIterator implements Iterator{
        private Node n;
        public LIterator(){
            this.n=head;
        }

        @Override
        public boolean hasNext() {
            return n.next!=null;
        }

        @Override
        public Object next() {
            n = n.next;
            return n.item;
        }
    }

    //Used to reverse the entire linked list
    public void reverse(){

        //Judge whether the current linked list is an empty linked list. If it is an empty linked list, end the operation. If not, call the overloaded reverse method to complete the inversion
        if (isEmpty()){
            return;
        }

        reverse(head.next);
    }

    //Reverses the specified node curr and returns the reversed node
    public Node reverse(Node curr){
        if (curr.next==null){
            head.next=curr;
            return curr;
        }
        //Recursively invert the next node of the current node curr; The return value is the previous node of the current node after the linked list is reversed
        Node pre = reverse(curr.next);
        //Let the next node of the returned node become the current node curr;
        pre.next=curr;
        //Make the next node of the current node null
        curr.next=null;
        return curr;
    }
//Test code
public static void main(String[] args) {
        //Create sequence table object
        LinkList<String> sl = new LinkList<>();
        //Test insertion
        sl.insert("Wang Xianzhi");
        sl.insert("Jian Jiuhuang");
        sl.insert("Li Chungang");
        sl.insert(1,"Xu Fengnian");

        for (String s : sl) {
            System.out.println(s);
        }

        System.out.println("------------------------------------------");

        //Test acquisition
        String getResult = sl.get(1);
        System.out.println("The result at index 1 is:"+getResult);
        //Test delete
        String removeResult = sl.remove(0);
        System.out.println("The deleted elements are:"+removeResult);
        //Test empty
        sl.clear();
        System.out.println("The number of elements in the cleared linear table is:"+sl.length());
    }


}

Bidirectional linked list

summary:

  • Bidirectional linked list, also known as bidirectional list, is a kind of linked list. It is composed of multiple nodes. Each node is composed of a data field and two pointer fields. The data field is used to store data. One pointer field is used to point to its successor node and the other pointer field is used to point to the predecessor node.
  • The data field of the head node of the linked list does not store data, the pointer field value pointing to the predecessor node is null, and the pointer field pointing to the successor node points to the first node that actually stores data.
    Bidirectional linked list TowWayLinkList class
  • Construction method: TowWayLinkList(): create a TowWayLinkList object
  • Member method:
    1.public void clear(): empty linear table
    2.publicboolean isEmpty(): judge whether the linear table is empty, return true if yes, and return false if No
    3.public int length(): get the number of elements in the linear table
    4.public T get(int i): read and return the value of the ith element in the linear table
    5. Public void insert (T): add an element to the linear table;
    6. Public void insert (int i, t, t): insert a data element with a value of T before the ith element of the linear table.
    7.public T remove(int i): delete and return the ith data element in the linear table.
    8. Public int indexof (T): returns the bit sequence number of the specified data element that appears for the first time in the linear table. If it does not exist, then
    Returns - 1.
    9.public T getFirst(): get the first element
    10.public T getLast(): get the last element
  • Member internal class: private class Node: node class
  • Member variables:
    1.private Node first: record the first node
    2.private Node last: record tail node
    2.private int N: record the length of the linked list
    Bidirectional linked list code demonstration
import java.util.Iterator;
public class TowWayLinkList<T> implements Iterable<T> {
    //First node
    private Node head;
    //Last node
    private Node last;

    //Length of linked list
    private int N;

    //Node class
    private class Node{
        public Node(T item, Node pre, Node next) {
            this.item = item;
            this.pre = pre;
            this.next = next;
        }
        //Store data
        public T item;
        //Point to previous node
        public Node pre;
        //Point to the next node
        public Node next;
    }

    public TowWayLinkList() {
       //Initialize head and tail nodes
        this.head = new Node(null,null,null);
        this.last=null;
        //Number of initialization elements
        this.N=0;
    }

    //Empty linked list
    public void clear(){
        this.head.next=null;
        this.head.pre=null;
        this.head.item=null;
        this.last=null;
        this.N=0;
    }

    //Get linked list length
    public int length(){
        return N;
    }

    //Determine whether the linked list is empty
    public boolean isEmpty(){
        return N==0;
    }

    //Get the first element
    public T getFirst(){
        if (isEmpty()){
            return null;
        }
        return head.next.item;
    }

    //Get the last element
    public T getLast(){
        if (isEmpty()){
            return null;
        }
        return last.item;
    }

    //Insert element t
    public void insert(T t){

        if (isEmpty()){
            //If the linked list is empty:

            //Create a new node
            Node newNode = new Node(t,head, null);
            //Let the new node be called the tail node
            last=newNode;
            //Let the head node point to the tail node
            head.next=last;
        }else {
            //If the linked list is not empty
            Node oldLast = last;

            //Create a new node
            Node newNode = new Node(t, oldLast, null);

            //Make the current tail node point to the new node
            oldLast.next=newNode;
            //Let the new node be called the tail node
            last = newNode;
        }

        //Number of elements + 1
        N++;

    }

    //Inserts the element t at the specified location i
    public void insert(int i,T t){
        //Find the previous node at position i
        Node pre = head;
        for(int index=0;index<i;index++){
            pre=pre.next;
        }
        //Find the node at position i
        Node curr = pre.next;
        //Create a new node
        Node newNode = new Node(t, pre, curr);
        //Let the next node of the previous node at i position become a new node
        pre.next=newNode;
        //Make the previous node at i position become a new node
        curr.pre=newNode;
        //Number of elements + 1
        N++;
    }

    //Gets the element at the specified location i
    public T get(int i){
        Node n = head.next;
        for(int index=0;index<i;index++){
            n=n.next;
        }
        return n.item;
    }

    //Find the position where the element t first appears in the linked list
    public int indexOf(T t){
        Node n = head;
        for(int i=0;n.next!=null;i++){
            n=n.next;
            if (n.next.equals(t)){
                return i;
            }
        }
        return -1;
    }

    //Delete the element at position i and return it
    public T remove(int i){
        //Find the previous node at position i
        Node pre = head;
        for(int index=0;index<i;index++){
            pre=pre.next;
        }
        //Find the node at position i
        Node curr = pre.next;
        //Find the next node at position i
        Node nextNode= curr.next;
        //Let the next node of the previous node of i position become the next node of i position
        pre.next=nextNode;
        //Let the previous node of the next node in position I become the previous node in position i
        nextNode.pre=pre;
        //Number of elements - 1
        N--;
        return curr.item;
    }

    @Override
    public Iterator<T> iterator() {
        return new TIterator();
    }

    private class TIterator implements Iterator{
        private Node n;
        public TIterator(){
            this.n=head;
        }
        @Override
        public boolean hasNext() {
            return n.next!=null;
        }

        @Override
        public Object next() {
            n=n.next;
            return n.item;
        }
    }
}
//Test class
public class TowWayLinkListTest {

    public static void main(String[] args) {
        //Create a two-way linked list object
        TowWayLinkList<String> sl = new TowWayLinkList<>();
        //Test insertion
        sl.insert("Yao Ming");
        sl.insert("Kobe");
        sl.insert("McGrady");
        sl.insert(1,"James");

        for (String s : sl) {
            System.out.println(s);
        }   
        System.out.println("The first element is:"+sl.getFirst());
        System.out.println("The last element is:"+sl.getLast());    
        //Test acquisition
        String getResult = sl.get(1);
        System.out.println("The result at index 1 is:"+getResult);
        //Test delete
        String removeResult = sl.remove(0);
        System.out.println("The deleted elements are:"+removeResult);
        //Test empty
        sl.clear();
        System.out.println("The number of elements in the cleared linear table is:"+sl.length());
    }

summary

Comparison between sequential list and linked list:

  • Compared with the linked list, the insertion efficiency of the sequential table is relatively low, and the size of the defined array is also fixed. Sometimes, the time-consuming increases sharply through the capacity expansion method. If there are many searches, it is recommended to use the sequential table.
  • The query performance of linked list is lower than that of sequential list. Therefore, if there are many query operations in our program, it is recommended to use sequential list, and there are many addition and deletion operations, it is recommended to use linked list.

Topics: Algorithm data structure linked list