Single linked list inversion? Interviewer are you sure you want to ask this?

Time:2021-4-20

preface:

Single linked list is a common and important data structure. As time goes by, many operation algorithms for single linked list have been derived. For example, we will talk about them in this articleReverse operation of single linked list

The following will explain the data structure of the single linked list in detail with some pictures, as well as the inversion of the single linked list through three ways (recursion, double needle method, loop traversal).

Single linked list inversion? Interviewer are you sure you want to ask this?

Data structure:

1. Data structure of single linked list:

Single linked list is a kind of linear structure, which is composed ofNodeIt’s made up of. And each node is composed of aData fieldTogether withPointer field (next)It’s made up of.      

① The structure of node is as follows:

  1. The data field of the node: data field is generally used to store data. (Note: the data field needs to specify the type. It can only store the data of the specified type and can’t put everything, right? How is it implemented in the code? usegeneric paradigm 。)
  2. The pointer field of the node: the next pointer field is generally the stored pointer to the next node; This pointer is actually a memory address, because the node object is stored in the heap memory of the JVM, so the next pointer field of the node is the address of the next node in the heap memory; In the code, the memory address of the object is assigned to its reference variable, soThe pointer field stores the reference variable of the next node object

Single linked list inversion? Interviewer are you sure you want to ask this?

② The structure of single linked list is as follows:(The figure below is a single linked list composed of three nodes

Single linked list inversion? Interviewer are you sure you want to ask this?

If you think about it, it seems that the knowledge of single linked list is clearer in your mind. Why don’t we hurry up and get out the data structure code of single linked list, and then think about how to reverse it, en!

Single linked list inversion? Interviewer are you sure you want to ask this?

code:

1. Node node class:

Create a node class, which provides two additional methods (creation method of single linked table and traversal method of single linked table);

Note: how to create a single linked list createLinkedList( ): the insertion mode of node isTail insertion methodIn fact, there areHead insertionMode of operation;

Extension: how to insert a node in a linked listHashMapIt’s used in,In JDK 1 . 7 is the head insertion method, JDK 1 . 8:00 is tail insertion

/**
 * @PACKAGE_NAME: com.lyl.linklist
 *@ classname: node class
 *@ Description: element of single linked list: node node
 * @Date: 2020-05-30 16:18
 **/
public class Node<T> {
    //  The data field of the node
    public T data;
    //The pointer field of the node
    public Node next;

    /**
     *  Construction method
     *@ param data data field value
     */
    public Node(T data) {
        this.data = data;
    }
    
    
     /**
     *Creating a single linked list (tail insertion)
     *@ return returns the header node
     */
    public static Node createLinkedList(){
        //Head node
        Node<String> head;

        Node<String> n = new Node<String>("111");
        Node<String> n1 = new Node<String>("222");
        Node<String> n2 = new Node<String>("333");
        //Specifies the header node
        head = n;
        n.next = n1;
        n1.next = n2;
        //Return to head node
        return head;
    }
    
    
    /**
     *List traversal
     * @param node
     */
    public static void traverse(Node node) {
        while (node != null) {
            System.out.print(node.data + " --> ");
            node = node.next;
        }
        System.out.print("null");
        System.out.println();
    }
}

2. Single linked list inversion:

① Recursive inversion:
/**
 * @PACKAGE_NAME: com.lyl.linklist
 * @ClassName: ReverseByRecursiveTest
 *@ Description: using recursion to realize single linked list inversion
 * @Date: 2020-05-30 17:01
 **/
public class ReverseByRecursiveTest {

    /**
     *Using recursion to realize single linked list inversion
     *Head node of @ param head linked list
     *@ return returns the inverted head node
     */
    public static Node reverse(Node head) {
        if (head == null || head.next == null) {
            return head;
        }
        //  Get the next node of the head node, use temp temporary node storage
        Node temp = head.next;
        //Recursive call
        Node node = reverse(head.next);
        //Point the pointer field of the next node of the head node to the head node
        temp.next = head;
        //  Set the pointer field of the head node to null
        head.next = null;
        return node;
    }

    // test
    public static void main(String[] args) {
        //Create a single linked list
        Node head = Node.createLinkedList();
        //Traverse the newly created single linked list
        System.out.print ("newly created single linked list");
        Node.traverse(head);
        //  Recursive inversion of single linked list
        Node newHead = reverse(head);
        //Traversing the inverted single linked list
        System.out.print (inverted single linked list):);
        Node.traverse(newHead);
    }
}

Operation output:

Newly created single linked list: 111 — > 222 — > 333 — > null
Inverted single linked list: 333 — > 222 — > 111 — > null

Figure out the calling process of recursive method:

(1) First, the header node (111 nodes in the data field) is passed into the reverse () method, and the method is pushed onto the stack

Single linked list inversion? Interviewer are you sure you want to ask this?

(2) When it is executed toNode node = reverse(head.next);Pass the node whose data field is 222 into the reverse() method and push the method onto the stack

Single linked list inversion? Interviewer are you sure you want to ask this?

(3) When it is executed toNode node = reverse(head.next);Pass the node with data field 333 into reverse ( ) Method, and push the method into the stack; And then when it comes toifWhen judging, it is found that the next node pointed to by the next pointer field of the node with data field 333 is null. At this time, the method returns the current head node (the node with data field 333)

Single linked list inversion? Interviewer are you sure you want to ask this?

(4) , Dangreverse(333) ;Method will continue to execute at this timereverse(222) ;Continue to execute the code following the recursive call, and after execution,reverse(222) Method out of stack:

Single linked list inversion? Interviewer are you sure you want to ask this?

(5) , Dangreverse(222) ;Method will continue to execute at this timereverse(111) ;Continue to execute the code following the recursive call, and after execution,reverse(111) Method out of stack:

Single linked list inversion? Interviewer are you sure you want to ask this?

(6) , Dangreverse(111) Method out of stack, thenThe recursive call endsThe structure of the single linked list in the final heap is as follows:

Single linked list inversion? Interviewer are you sure you want to ask this?

Finally, the recursive call is finished. This graph is too laborious and takes too much timeProcessOn

② Loop traversal + auxiliary space inversion:
/**
 * @PACKAGE_NAME: com.lyl.linklist
 * @ClassName: ReverseByTraverseTest
 *@ Description: use loop traversal + auxiliary space for single linked list inversion
 * @Date: 2020-05-30 19:11
 **/
public class ReverseByTraverseTest {

    /**
     *Using traversal + auxiliary space to reverse linked list
     * @param head
     *@ return returns the inverted head node
     */
    public static Node reverse(Node head) {
        //List set auxiliary space
        List<Node> list = new ArrayList<Node>();

        while (head != null) {
            list.add(head);
            head = head.next;
        }

        for (int i = list.size() - 1; i > 0; i--) {
            Node n = list.get(i);
            Node n1 = list.get(i-1);
            n.next = n1;
            n1.next = null;
        }
        //Return to head node
        return list.get(list.size() - 1);
    }


    // test
    public static void main(String[] args) {
        //Create a single linked list
        Node head = Node.createLinkedList();
        //Traverse the newly created single linked list
        System.out.print ("newly created single linked list");
        Node.traverse(head);
        //Recursive inversion of single linked list
        Node newHead = reverse(head);
        //  Traversing the inverted single linked list
        System.out.print (inverted single linked list):);
        Node.traverse(newHead);
    }
}
③ , double pointer + auxiliary temporary node to realize inversion:
/**
 * @PACKAGE_NAME: com.lyl.linklist
 * @ClassName: ReverseByDoublePointerTest
 *@ Description: use double pointer + auxiliary temporary node to realize single linked list inversion
 * @Date: 2020-05-30 19:17
 **/
public class ReverseByDoublePointerTest {

    /**
     *Using double pointer and auxiliary temporary node to reverse linked list
     * @param head
     *@ return returns the inverted head node
     */
    public static Node reverse(Node head) {
        //Current node pointer
        Node current ;
        //Previous node pointer
        Node previous;
        //Current node pointer初始化指向头结点
        current = head;
        //Previous node pointer初始化为 null
        previous = null;

        while(current != null){
            //The auxiliary temporary node stores the next node of the current node
            Node temp = current.next;
            //  The next node of the current node points to the node pointed to by the previous node pointer
            current.next = previous;
            //  Then the previous node pointer moves forward one node, and both the current node pointer and the current node pointer point to the current node
            previous = current;
            //Current node pointer也向前移动一个节点,也就是移动到了当前节点的下一个节点,就是临时节点指向的节点
            current = temp;
        }
        //Return to head node
        return previous;
    }


    // test
    public static void main(String[] args) {
        //Create a single linked list
        Node head = Node.createLinkedList();
        //Traverse the newly created single linked list
        System.out.print ("newly created single linked list");
        Node.traverse(head);
        //Recursive inversion of single linked list
        Node newHead = reverse(head);
        //Traversing the inverted single linked list
        System . out . print (" Inverted single linked list: ");
        Node.traverse(newHead);
    }
}

Single linked list inversion? Interviewer are you sure you want to ask this?

End, finally finished, this article focuses on the next recursive call process, because recursion is generally not easy to understand.

❤ Don’t forget to leave your study footprints [ give the thumbs-up + Collection + comment ] Hey, hey

All those who don’t like articles are “playing hooligans”. Hey hey (◍◍◍ノ゙)! Make a joke, move your little hand, the praise will be finished, you each out of a power (praise + comment) will let more learners join in! Thank you very much.  ̄ω ̄=

Recommended Today

Everyone loves kubernetes. Doesn’t docker smell good?

Opening When it comes to docker, many people first think that it is a virtualization container, so it is particularly easy to fall into a misunderstanding that docker only adds another layer to the Linux operating system, just like running a VMware on the OS. Docker must be slow and complex. It doesn’t look as […]