Learn these linked list algorithm questions, and you will no longer be afraid of handwritten linked lists for interviews.

Learn these linked list algorithm questions, and you will no longer be afraid of handwritten linked lists for interviews.

> The author's writing skills are still shallow, if there is anything wrong, please point out generously, I will definitely be grateful

During the interview, I am often asked to write the code about the linked list by hand. The following are the questions I have been asked in the interview. Of course, what I wrote is not necessarily the optimal solution. If there is a better solution, you are welcome to point it out.

For the convenience of everyone to watch, I will list the topics first

  • Delete the Nth last node in the linked list
  • linked list reversal
  • Merge two sorted linked lists
  • Find the middle node of the linked list

Delete the Nth last node in the linked list

Question: Given a linked list, delete the nth node from the bottom of the linked list and return the head node of the linked list.

给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.

In the problem of linked list, sometimes a pointer cannot solve the problem, then we add another pointer. In general, two pointers can solve most problems

The above is the linked list we defined. For example, if we want to delete the Nth node from the bottom, then we define two pointers, a fast pointer and a slow pointer. The fast pointer is N steps faster than the slow pointer, and then the fast and slow pointers move forward together, so just Nullwhen the fast pointer goes, the slow pointer points to the node we want to delete.

For example, if we want to delete the penultimate node, then the initialized pointer pointer points to the following.

After traversing the pointer as follows, we can see that the pointer on the left points to the node we want to delete

Part of the code is as follows

public void deleteNodeForN(Node head, int n){

    Node left = head;
    Node right = head;
    int i = 0;
    while (right!=null && i < n){
        right = right.getNext();
        i++;
    }

    while (right!=null){
        left = left.getNext();
        right = right.getNext();
    }
	// 遍历完后删除左节点
    deleteNode(left);

}

linked list reversal

Question: Reverse a singly linked list.

输入: 0->1->2->3->4->5->NULL
输出: 5->4->3->2->1->0->NULL

> There is no problem in the linked list that cannot be solved by adding a pointer. If there is, then add a pointer.

Solution 1: Add a pointer

In the above linked list to delete the Nth node, we added two pointers to solve the problem, then what should we do if we want to reverse a linked list? Two pointers are not enough, we need three pointers to define the current node, the previous node of the current node, and the back node of the current node. Of course, this method is a solution that does not take up space and is fast.

Or we define a linked list, so what is the pointer effect we want? Next, we will use the diagram to demonstrate step by step how to use three pointers to turn the linked list over. You don't need to look at the solution answer I gave at the end. You can try to look at my diagram and write the code yourself to see if you can write it.

Part of the code display


public Node reversalNodeThree(Node head) {
    if (head == null || head.getNext() == null){
        return head;
    }

    Node preNode = null;
    Node nextNode = null;
    while (head != null){
        nextNode = head.getNext();
        head.setNext(preNode);
        preNode = head;
        head = nextNode;
    }
    return preNode;
}

Solution 2: Recursion

> The key to recursive code is how to decompose the big problem into the law of small problems, and write the recursive formula based on this, and then consider the termination condition.

When writing recursive code, our thinking must not be trapped in it step by step, it will be easy to be fooled by trapping it. In fact, the essence of recursion is to decompose the execution of small tasks, and our correct way of thinking shields the details of recursion, assuming that the result we want is already behind, and then we only want to take the first step.

Let's take the reverse linked list as an example, how to use recursive thinking to think, and how to turn our thinking into code.

> Here the next node of node 0 is not node 5, but our large node on the gray background

Or the above linked list as an example, we want to reverse, assuming that all the nodes following the first node have been reversed successfully, then what do we do next? I believe everyone here will know it, which is equivalent to the conversion of two nodes.

Node(0).getNext().setNext(Node(0));
Node(0).setNext(null);

  • Termination condition: When the passed Node is null or the passed Node.next is null. Indicates that the incoming is an empty node or just a node, no need to reverse

Using the above termination conditions and the analyzed code, we can write the following code for recursively reversing a chain.

public Node reversalNodeTwo(Node head){

    if (head == null || head.getNext() == null){
        return head;
    }

    Node reHead = reversalNodeTwo(head.getNext());

    head.getNext().setNext(head);

    head.setNext(null);

    return reHead;

}

Merge two sorted linked lists

Question: Merge two sorted linked lists into a new sorted linked list and return. The new linked list is formed by splicing all the nodes of the given two linked lists.

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

iterate

The iterative way of merging two linked lists solves the problem by means of pointers. Join We now have the following two linked lists. We will define two pointers to point to the heads of the two linked lists to start a one-to-one comparison, and the smaller one will move the node out and move the pointer backwards. until null . Next we break down each step with pictures. You can practice coding by yourself according to the prompts in the picture, and the answers will be attached later.

Part of the code display

public Node mergeTwoListTwo(Node nodeOne, Node nodeTwo){

    AboutLinkedList mergeTwoList = new AboutLinkedList();
    Node headNodeOne = nodeOne;
    Node headNodeTwo = nodeTwo;

    while (headNodeOne!=null || headNodeTwo!=null){

        if (headNodeOne == null || headNodeOne.getNum() > headNodeTwo.getNum()){
            mergeTwoList.addNode(headNodeTwo);
            Node pre = headNodeTwo;
            headNodeTwo = headNodeTwo.getNext();
            pre.setNext(null);
        }else {
            mergeTwoList.addNode(headNodeOne);
            Node pre = headNodeOne;
            headNodeOne = headNodeOne.getNext();
            pre.setNext(null);
        }
    }
    return mergeTwoList.head.getNext();
}

Find the middle node of the linked list

Question: Find the middle node of a linked list

输入:0->1->2->3->4
输出:2

pointer

Generally speaking, if we can use pointers for linked list problems, it is the best solution whether it is time or space. In fact, there is a little trick here, that is to define two pointers (fast and slow pointers), and the fast pointers go two nodes at a time. The slow pointer goes one node at a time. In this way, when the fast pointer reaches the end, the slow pointer just goes to the middle position. Next, let's use the diagram to more intuitively feel how the pointer moves. You can write the code yourself according to the demonstration in the figure, and then look at the code I gave at the end. It will be more memorable

Part of the code display

public Node getNodeForCenter(Node head){
    if (head == null){
        return null;
    }else if (head.getNext() == null){
        return head;
    }
    Node slow = head;
    Node fast = head;
    while (fast!=null && fast.getNext()!=null){
        slow = slow.getNext();
        fast = fast.getNext().getNext();
    }
    return slow;
}

code address

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324115642&siteId=291194637