Force button brush question: linked list

Posted by mbarmawi on Tue, 08 Feb 2022 07:12:38 +0100

1290. Binary linked list to integer

Topic introduction

Give you a reference node head of single linked list. The value of each node in the linked list is either 0 or 1. It is known that this linked list is a binary representation of an integer number.

Please return the decimal value of the number represented by the linked list.

Example 1:

Input: head = [1,0,1]
Output: 5
 Explanation: binary number (101) Convert to decimal (5)

Example 2:

Input: head = [0]
Output: 0

Example 3:

Input: head = [1]
Output: 1

Example 4:

Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0]
Output: 18880

Example 5:

Input: head = [0,0]
Output: 0

Tips:

  • The linked list is not empty.
  • The total number of nodes in the linked list shall not exceed 30.
  • The value of each node is either 0 or 1.

Source: LeetCode
Link: https://leetcode-cn.com/problems/convert-binary-number-in-a-linked-list-to-integer
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Topic realization

Because the binary representation of numbers is stored from high to low in the linked list, we can use the method of binary to decimal to get the decimal value of numbers while traversing the linked list. Take the binary linked list given in example 1 as an example:

The following uses (n)2 to indicate that n is a binary integer.

The value of the first node of the linked list is 1, which is the highest bit of binary. In decimal decomposition, the index of 22 corresponding to 1 as a coefficient is 2, because the length of the linked list is 3. Is it necessary for us to know the length of the linked list before we can determine the index 2? The answer is unnecessary.

Normal calculation: ÷ 2 = Quotient... Remainder
5 ÷ 2 = 2 Yu 1
2 ÷ 2 = 1 Yu 0
1 ÷ 2 = 0 Yu 1
===> Get binary 101

Push back: quotient x 2 + remainder = number
-> 0 x 2 + 1 = 1
-> 1 x 2 + 0 = 2
-> 2 x 2 + 1 = 5
===> Get decimal 5
class Solution {
    public int getDecimalValue(ListNode head) {
        int ans = 0;
        while (head != null) {
            ans = ans * 2 + head.val;
            head = head.next;
        }
        return ans;
    }
}

138. Copy linked list with random pointer

Topic introduction

Give you a linked list with a length of n. each node contains an additional random pointer random, which can point to any node or empty node in the linked list.

Construct a deep copy of this linked list. The deep copy should consist of exactly n new nodes, in which the value of each new node is set to the value of its corresponding original node. The next pointer and random pointer of the new node should also point to the new node in the replication linked list, and these pointers in the original linked list and replication linked list can represent the same linked list state. The pointer in the copy linked list should not point to the node in the original linked list.

For example, if there are two nodes X and Y in the original linked list, where x.random -- > y. Then the corresponding two nodes X and Y in the copy linked list also have x.random -- > y.

Returns the header node of the copy linked list.

A linked list composed of n nodes is used to represent the linked list in input / output. Each node is represented by a [val, random_index]:

  • Val: one represents node Integer of val.
  • random_index: the node index pointed by the random pointer (range from 0 to n-1); null if it does not point to any node.

Your code only accepts the head node of the original linked list as the incoming parameter.

Example 1:

Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output:[[7,null],[13,0],[11,4],[10,2],[1,0]]

Example 2:

Input: head = [[1,1],[2,1]]
Output:[[1,1],[2,1]]

Example 3:

Input: head = [[3,null],[3,0],[3,null]]
Output:[[3,null],[3,0],[3,null]]

Example 4:

Input: head = []
Output:[]
Explanation: the given linked list is null (null pointer), so it returns null. 

Tips:

  • 0 <= n <= 1000
  • -10000 <= Node.val <= 10000
  • Node.random is empty (null) or points to a node in the linked list.

Same title:

Source: LeetCode
Link: https://leetcode-cn.com/problems/copy-list-with-random-pointer
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Topic realization

We traverse the entire linked list. In the process of traversal, we use the old node as the key and the new node as the value to store in the hash table.

Then traverse the whole linked list again, get the new node through the old node, and then assign next and random values to the new node.

class Solution {
    public Node copyRandomList(Node head) {
        if (head == null) return null;
        HashMap<Node, Node> hashMap = new HashMap<>();

        Node temp = head;
        while (temp != null) {
            hashMap.put(temp, new Node(temp.val));
            temp = temp.next;
        }

        temp = head;
        while (temp != null) {
            hashMap.get(temp).next = hashMap.get(temp.next);
            hashMap.get(temp).random = hashMap.get(temp.random);
            temp = temp.next;
        }

        return hashMap.get(head);
    }
}

141. Circular linked list

Topic introduction

Given a linked list, judge whether there are links in the linked list.

If there is a node in the linked list that can be reached again by continuously tracking the next pointer, there is a ring in the linked list. In order to represent the rings in a given linked list, we use the integer pos to represent the position where the tail of the linked list is connected to the linked list (the index starts from 0). If pos is - 1, there is no ring in the linked list.

Note: pos is not passed as a parameter, but only to identify the actual situation of the linked list.

Returns true if there are links in the linked list. Otherwise, false is returned.

Example 1:

Input: head = [3,2,0,-4], pos = 1
 Output: true
 Explanation: there is a ring in the linked list, and its tail is connected to the second node.

Example 2:

Input: head = [1,2], pos = 0
 Output: true
 Explanation: there is a ring in the linked list, and its tail is connected to the first node.

Example 3:

Input: head = [1], pos = -1
 Output: false
 Explanation: there are no links in the linked list.

Tips:

  • The number range of nodes in the linked list is [0, 104]
  • -105 <= Node.val <= 105
  • pos is - 1 or a valid index in the linked list.

Advanced:

  • Can you solve this problem with O(1) (i.e., constant) memory?

Source: LeetCode
Link: https://leetcode-cn.com/problems/linked-list-cycle
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Topic realization

To solve the circular linked list, we need to use fast and slow pointers. The fast pointer moves two nodes at a time, and the slow pointer moves one node at a time. For example:

When running 5000 meters in the sports meeting, the fast runner will surely have a chance to catch up with the slow runner. Similarly, this is the principle of the fast and slow pointer.

Before judging whether a linked list has rings, we might as well take a look at the case that the linked list has no rings. The number of nodes in the linked list may be odd or even. The following two cases are shown:

When the number of linked lists is odd, the fast pointer walks two nodes at a time and the slow pointer walks one node at a time. The process is as follows:

At this time, we find that the fast pointer has pointed to the position of the last element. At this time, the slow pointer just points to the middle element, and the end condition is: fast next = null .

When the number of linked lists is even, the fast pointer walks two nodes at a time and the slow pointer walks one node at a time. The process is as follows:

At this time, we find that the fast pointer has pointed to the null position. At this time, the end condition is: fast = null.

Through the analysis of the above two diagrams, as long as there is no ring in the linked list, it shows that the fast pointer must meet the following requirements: fast = = null | fast next == null .

If there are links in the linked list, then the fast pointer and the slow pointer will always intersect at a certain time. The intersection proves that there are links, just like the circular runway in the playground.

public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null) return false;
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) return true;
        }
        return false;
    }
}

160. Intersecting linked list

Topic introduction

Write a program to find the starting node where two single linked lists intersect.

As shown in the following two linked lists:

The intersection begins at node c1.

Example 1:

Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
 Output: Reference of the node with value = 8
 Input explanation: the value of intersection node is 8 (note that if two linked lists intersect, it cannot be 0). The linked list starts from the respective header A by [4,1,8,4,5],Linked list B by [5,0,1,8,4,5]. stay A In, there are 2 nodes before the intersecting node; stay B In, there are 3 nodes before the intersection node.

Example 2:

Input: intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
 Output: Reference of the node with value = 2
 Input explanation: the value of intersection node is 2 (note that if two linked lists intersect, it cannot be 0). The linked list starts from the respective header A by [0,9,1,2,4],Linked list B by [3,2,4]. stay A In, there are 3 nodes before the intersection node; stay B In, there is 1 node before the intersection node.

Example 3:

Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
 Output: null
 Input explanation: the linked list starts from the respective header A by [2,6,4],Linked list B by [1,5]. Because the two linked lists do not intersect, so intersectVal Must be 0, and skipA and skipB Can be any value.
Explanation: the two linked lists do not intersect, so they return null. 

be careful:

  • If the two linked lists have no intersection, null is returned.
  • After returning the results, the two linked lists must still maintain their original structure.
  • It can be assumed that there is no loop in the whole linked list structure.
  • The program shall meet the O(n) time complexity as much as possible, and only use O(1) memory.

Same title:

Source: LeetCode
Link: https://leetcode-cn.com/problems/intersection-of-two-linked-lists
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Topic realization

When we get this question, we will feel a little difficult and have no way to start. In fact, we might as well look at it from another angle, as shown in the following figure:

We only need to make up the length of the A linked list and the length of the B linked list, and then judge whether the node addresses in the first row of the following figure and the node addresses in the second row of the following figure are equal from left to right.

Take the first row after the completion of the above figure as an example. Once the scan is completed, A linked list finds no intersecting nodes. When curA == null is found at the end of the linked list, he will immediately start to search backward from B linked list until he finds A node with the same address value, which means that an intersecting node is found. It doesn't matter if B linked list searches again, Since the length of the upper and lower linked lists in the figure above is the same after completion, null will be scanned in the end. Since null == null is equal, the loop will exit naturally, and curA, that is, null, is returned at this time, which is also correct.

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        ListNode curA = headA;
        ListNode curB = headB;
        while (curA != curB) {// Note: the address value is judged here
            curA = (curA == null) ? headB : curA.next;
            curB = (curB == null) ? headA : curB.next;
        }
        return curA;
    }
}

2. Add two numbers

Topic introduction

Give you two non empty linked lists to represent two non negative integers. They store each number in reverse order, and each node can store only one number.

Please add the two numbers and return a linked list representing sum in the same form.

You can assume that neither number starts with 0 except the number 0.

Example 1:

Input: l1 = [2,4,3], l2 = [5,6,4]
Output:[7,0,8]
Explanation: 342 + 465 = 807.

Example 2:

Input: l1 = [0], l2 = [0]
Output:[0]

Example 3:

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output:[8,9,9,9,0,0,0,1]

Tips:

  • The number of nodes in each linked list is within the range [1, 100]
  • 0 <= Node.val <= 9
  • The number represented in the title data guarantee list does not contain leading zeros

Same title:

Source: LeetCode
Link: https://leetcode-cn.com/problems/add-two-numbers
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Topic realization

Take two linked lists as of the same length for traversal. If a linked list is short, fill 0 in front, such as 987 + 23 = 987 + 023 = 1010.

The carry problem of the previous bit needs to be considered during each bit calculation, and the carry value also needs to be updated after the current bit calculation.

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode newHead = new ListNode(0);
        ListNode newLast = newHead;
        int carry = 0;
        while (l1 != null || l2 != null || carry != 0) {
            // Null, default zero
            int l1Val = l1 != null ? l1.val : 0;
            int l2Val = l2 != null ? l2.val : 0;
            // Add two numbers
            int sumVal = l1Val + l2Val + carry;
            // Update carry value
            carry = sumVal / 10;
            // Save single digit
            ListNode sumNode = new ListNode(sumVal % 10);
            newLast.next = sumNode;
            newLast = sumNode;
            // Move back separately
            if (l1 != null) l1 = l1.next;
            if (l2 != null) l2 = l2.next;
        }
        return newHead.next;
    }
}

203. Remove linked list elements

Topic introduction

Give you a head node of the linked list and an integer val. please delete all nodes in the linked list that meet the requirements Val = = Val node and returns a new header node.

Example 1:

Input: head = [1,2,6,3,4,5,6], val = 6
 Output:[1,2,3,4,5]

Example 2:

Input: head = [], val = 1
 Output:[]

Example 3:

Input: head = [7,7,7,7], val = 7
 Output:[]

Tips:

  • The nodes in the list are in the range [0, 104]
  • 1 <= Node.val <= 50
  • 0 <= k <= 50

Same title:

Source: LeetCode
Link: https://leetcode-cn.com/problems/remove-linked-list-elements
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Topic realization

We can create a new linked list and traverse the nodes in the original linked list. If the value of this node is not equal to the value of val, it will be added to the new linked list. To facilitate appending, we also need to set a newLast pointer to point to the last node. During initialization, newHead and newLast should point to the same node. Given val = 6 is known.

When the head pointer points to the 1 node of the original linked list and does not match the given val, it is appended to the new linked list. At this time, the next node of newLast should point to the head node, and then newLast should point to the head node. After the above operations are completed, the head pointer needs to be moved back one bit, that is, head = head next; .

When the head pointer points to the 2 nodes of the original linked list and does not match the given val, it is appended to the new linked list. At this time, the next node of newLast should point to the head node, and then newLast should point to the head node. After the above operations are completed, the head pointer needs to be moved back one bit, that is, head = head next; .

When the head pointer points to the 6 nodes of the original linked list, which is equal to the given val, it indicates that there is no need to append this time, but the head pointer needs to move back one bit, that is, head = head next; .

According to the above operations, scan backward until the head is null and exit. At this time, more than half of our task has been completed. There is another small problem, that is, the next node of the node pointed to by newLast is not null. We need to manually set it to null. This step is very important. Otherwise, the answer cannot pass.

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode newHead = new ListNode(0);
        ListNode newLast = newHead;
        while (head != null) {
            if (head.val != val) {
                newLast.next = head;
                newLast = head;
            }
            head = head.next;
        }
        newLast.next = null;
        return newHead.next;
    }
}

206. Reverse linked list

Topic introduction

Give you the head node of the single linked list. Please reverse the linked list and return the reversed linked list.

Example 1:

Input: head = [1,2,3,4,5]
Output:[5,4,3,2,1]

Example 2:

Input: head = [1,2]
Output:[2,1]

Example 3:

Input: head = []
Output:[]

Tips:

  • The number range of nodes in the linked list is [0, 5000]
  • -5000 <= Node.val <= 5000

Same title:

Source: LeetCode
Link: https://leetcode-cn.com/problems/reverse-linked-list
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Topic realization

For the reversal of the linked list, we first need to define a new chain header, scan all nodes of the original linked list from left to right, and then add them to the left of the new header in turn.

First, cache the next node of the current head node, that is, node 2, because we need to operate on the head node, make the next of the head node point to newHead, then make the newHead point to head, and then make the head point to the cached node 2 again. After completing the above operations, see the following figure:

Then cache the next node of the current head node, that is, node 3, because we need to operate on the head node, make the next of the head node point to newHead, then make the newHead point to head, and then make the head point to the cached node 3 again. After completing the above operations, see the following figure:

Then cache the next node of the current head node, that is, the null node, because we need to operate on the head node, make the next of the head node point to the newHead, then make the newHead point to the head, and then make the head point to the cached null node again. After completing the above operations, see the following figure:

After the above operations, the head node is null, end the loop, and then return to newHead.

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode newHead = null;
        ListNode tmpNode = null;
        while (head != null) {
            tmpNode = head.next;
            head.next = newHead;
            newHead = head;
            head = tmpNode;
        }
        return newHead;
    }
}

21. Merge two ordered linked lists

Topic introduction

Merge the two ascending linked lists into a new ascending linked list and return. The new linked list is composed of all nodes of a given two linked lists.

Example 1:

Input: l1 = [1,2,4], l2 = [1,3,4]
Output:[1,1,2,3,4,4]

Example 2:

Input: l1 = [], l2 = []
Output:[]

Example 3:

Input: l1 = [], l2 = [0]
Output:[0]

Tips:

  • The number of nodes in the two linked lists ranges from [0, 50]
  • -100 <= Node.val <= 100
  • l1 and l2 are arranged in non decreasing order

Same title:

Source: LeetCode
Link: https://leetcode-cn.com/problems/merge-two-sorted-lists
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Topic realization

We need to create a virtual header, and then loop through the nodes pointed by l1 and L2 at the same time, if l1 val <= l2. Val, we will add it to the virtual header node.

At this point, we find that l1 points to null, so we exit the loop and append l2 directly to newLast.

After the above operations, we only need to return newhead Next.

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;

        ListNode newHead = new ListNode(0);
        ListNode newLast = newHead;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                newLast.next = l1;
                newLast = l1;
                l1 = l1.next;
            } else {
                newLast.next = l2;
                newLast = l2;
                l2 = l2.next;
            }
        }

        if (l1 != null) newLast.next = l1;
        if (l2 != null) newLast.next = l2;

        return newHead.next;
    }
}

23. Merge K ascending linked lists

Topic introduction

Give you a linked list array, each linked list has been arranged in ascending order.

Please merge all linked lists into an ascending linked list and return to the merged linked list.

Example 1:

Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output:[1,1,2,3,4,4,5,6]
Explanation: the linked list array is as follows:
[
  1->4->5,
  1->3->4,
  2->6
]
Combine them into an ordered linked list.
1->1->2->3->4->4->5->6

Example 2:

Input: lists = []
Output:[]

Example 3:

Input: lists = [[]]
Output:[]

Tips:

  • k == lists.length
  • 0 <= k <= 104
  • 0 <= lists[i].length <= 500
  • -104 <= lists[i][j] <= 104
  • lists[i] in ascending order
  • lists[i]. The sum of length does not exceed 104

Topics used:

Source: LeetCode
Link: https://leetcode-cn.com/problems/merge-k-sorted-lists
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Topic realization

The implementation idea is actually very simple. We only need to merge the linked lists in the given array in pairs until there is one left, and then we can complete the merging of all linked lists. The diagram is as follows:

class Solution {
    // https://leetcode-cn.com/problems/merge-k-sorted-lists/
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) return null;

        int step = 1;
        while (step < lists.length) {
            int nextStep = step * 2;
            for (int i = 0; i + step < lists.length; i += nextStep) {
                lists[i] = mergeTwoLists(lists[i], lists[i + step]);
            }
            step = nextStep;
        }

        return lists[0];
    }

    // https://leetcode-cn.com/problems/merge-two-sorted-lists/
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;

        ListNode newHead = new ListNode(0);
        ListNode newLast = newHead;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                newLast.next = l1;
                newLast = l1;
                l1 = l1.next;
            } else {
                newLast.next = l2;
                newLast = l2;
                l2 = l2.next;
            }
        }

        if (l1 != null) newLast.next = l1;
        if (l2 != null) newLast.next = l2;

        return newHead.next;
    }
}

234. Palindrome linked list

Topic introduction

Please judge whether a linked list is a palindrome linked list.

Example 1:

input: 1->2
 output: false

Example 2:

input: 1->2->2->1
 output: true

Advanced:

  • Can you solve this problem with O(n) time complexity and O(1) space complexity?

Same title:

Topics used:

Source: LeetCode
Link: https://leetcode-cn.com/problems/palindrome-linked-list
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Topic realization

If we want to judge whether the linked list is a palindrome linked list, we need to first find the intermediate node of the linked list. If there are two intermediate nodes when the number of linked lists is even, the second intermediate node is used as the intermediate node. Then reverse the right half of the linked list starting from the middle node. After the reverse is completed, we only need to compare whether the elements corresponding to lHead and rHead are the same one by one. It is obvious that we need to restore the reverse of the right half of the linked list after judging by referring to the second figure in the figure below.

class Solution {
    // https://leetcode-cn.com/problems/palindrome-linked-list/
    public boolean isPalindrome(ListNode head) {
        // Critical condition check
        if (head == null || head.next == null) return true;
        // Find intermediate node
        ListNode midNode = middleNode(head);
        // Reverse right half
        ListNode newHead = reverseList(midNode);
        // Redefine variables
        ListNode lHead = head;
        ListNode rHead = newHead;
        // Start judging
        boolean isPalindrome = true;
        while (lHead != null && rHead != null) {
            if (lHead.val != rHead.val) {
                isPalindrome = false;
                break;
            }
            lHead = lHead.next;
            rHead = rHead.next;
        }
        // Restore the right half
        reverseList(newHead);
        // Return the judgment result
        return isPalindrome;
    }

    // https://leetcode-cn.com/problems/middle-of-the-linked-list/
    public ListNode middleNode(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }

    // https://leetcode-cn.com/problems/reverse-linked-list/
    public ListNode reverseList(ListNode head) {
        ListNode newHead = null;
        ListNode tmpNode = null;
        while (head != null) {
            tmpNode = head.next;
            head.next = newHead;
            newHead = head;
            head = tmpNode;
        }
        return newHead;
    }
}

86. Separate linked list

Topic introduction

Give you a head node of the linked list and a specific value X. please separate the linked list so that all nodes less than x appear before nodes greater than or equal to X.

You should keep the initial relative position of each node in both partitions.

Example 1:

Input: head = [1,4,3,2,5,2], x = 3
 Output:[1,2,2,4,3,5]

Example 2:

Input: head = [2,1], x = 2
 Output:[1,2]

Tips:

  • The number of nodes in the linked list is within the range [0, 200]
  • -100 <= Node.val <= 100
  • -200 <= x <= 200

Same title:

Source: LeetCode
Link: https://leetcode-cn.com/problems/partition-list
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Topic realization

We now need to separate the linked list so that all nodes less than x appear before nodes greater than or equal to X.

Therefore, we will create two new head nodes, one is the left head node and the other is the right head node. The left head node stores nodes less than x, while the right head node stores nodes greater than or equal to X. in order to facilitate the addition of new nodes, we will create two pointers to the tail node respectively, as shown in the following figure:

Loop through all nodes in the original linked list, place nodes less than x on the left linked list and nodes greater than or equal to X on the right linked list.

At present, the head points to 1 node, which is less than x, so it is directly connected to the left chain list, and then the head moves back one node.

Then head points to 4 nodes, which is greater than x, so it is directly connected to the right linked list, and then head moves back one node.

According to the above rules, scan all nodes of the original linked list from left to right until it stops when it meets a null node, and then splice the left linked list and the right linked list into one piece.

However, it should be noted that the next reference of the last element of the right linked list, that is, the node pointed to by rLast, is not necessarily null. Therefore, we need to set it manually.

class Solution {
    public ListNode partition(ListNode head, int x) {
        if (head == null) return null;          // Judge whether the incoming linked list is empty
        ListNode lHead = new ListNode(0);   // Create virtual left head node
        ListNode rHead = new ListNode(0);   // Create virtual right head node
        ListNode lLast = lHead;     // By default, the left last points to the left head
        ListNode rLast = rHead;     // By default, the last on the right points to the head on the right
        while (head != null) {
            if (head.val < x) {
                lLast.next = head;
                lLast = head;
            } else {
                rLast.next = head;
                rLast = head;
            }
            head = head.next;
        }
        lLast.next = rHead.next;    // Splice two linked lists
        rLast.next = null;          // Remove the last node pointing
        return lHead.next;          // Returns the first element of the linked list
    }
}

876. Intermediate node of linked list

Topic introduction

Given a non empty single linked list with head node, return the intermediate node of the linked list.

If there are two intermediate nodes, the second intermediate node is returned.

Example 1:

Input:[1,2,3,4,5]
Output: node 3 in this linked list (Serialization form:[3,4,5])
The returned node value is 3. (The serialization expression of this node in the evaluation system is [3,4,5]). 
Notice that we returned a ListNode Object of type ans,So:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, as well as ans.next.next.next = NULL.

Example 2:

Input:[1,2,3,4,5,6]
Output: node 4 in this linked list (Serialization form:[4,5,6])
Since the linked list has two intermediate nodes with values of 3 and 4 respectively, we return the second node.

Tips:

  • The number of nodes in the given linked list is between 1 and 100.

Source: LeetCode
Link: https://leetcode-cn.com/problems/middle-of-the-linked-list
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Topic realization

We use fast and slow pointers to find the middle nodes of the linked list. Generally speaking, the number of a linked list can only be in two cases, odd or even. Let's discuss it separately.

When the number of linked lists is odd, the fast pointer walks two nodes at a time and the slow pointer walks one node at a time. The process is as follows:

At this time, we find that the fast pointer has pointed to the position of the last element. At this time, the slow pointer just points to the middle element, and the end condition is: fast next = null .

When the number of linked lists is even, the fast pointer walks two nodes at a time and the slow pointer walks one node at a time. The process is as follows:

At this time, we find that the fast pointer has pointed to the null position. At this time, since the linked list has two intermediate nodes with values of 3 and 4 respectively, we return the second node.

The slow pointer just points to the second node 4 in the middle, and the end condition is: fast = null.

class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
}

Just imagine, if we expand this topic, first of all, the situation of odd numbers is the same, which will not be considered here. When the number of linked lists is even, take the above figure as an example. Since the linked list has two intermediate nodes with values of 3 and 4 respectively, we return the first node. How to achieve it?

We find that when the fast pointer fast reaches the penultimate element position, the slow pointer slow is just at the first position of the two intermediate nodes, and the end condition is: fast next. next = null.

class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
}

Interview question 02.03 Delete intermediate node

Topic introduction

If a node in the linked list is neither the header node nor the tail node, it is called the "intermediate node" of the linked list.

Suppose you know an intermediate node of the linked list, please implement an algorithm to delete the node from the linked list.

For example, the incoming node c (located in the one-way linked list a - > b - > c - > D - > e - > F) is deleted, and the remaining linked list is a - > b - > D - > e - > F

Example:

Input: node 5 (located in one-way linked list 4)->5->1->9 (medium)
Output: do not return any data, delete the incoming node 5 from the linked list, and change the linked list to 4->1->9

Source: LeetCode
Link: https://leetcode-cn.com/problems/delete-middle-node-lcci
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Topic realization

Use the next node to replace the current node, so as to achieve the purpose of deletion.

class Solution {
    public void deleteNode(ListNode node) {
        node.val = node.next.val;
        node.next = node.next.next;
    }
}

Interview question 02.08 Loop detection

Topic introduction

Given a linked list, if it is a linked list, implement an algorithm to return the beginning node of the loop.

If there is a node in the linked list that can be reached again by continuously tracking the next pointer, there is a ring in the linked list. In order to represent the rings in a given linked list, we use the integer pos to represent the position where the tail of the linked list is connected to the linked list (the index starts from 0). If pos is - 1, there is no ring in the linked list. Note: pos is not passed as a parameter, but only to identify the actual situation of the linked list.

Example 1:

Input: head = [3,2,0,-4], pos = 1
 Output: tail connects to node index 1
 Explanation: there is a ring in the linked list, and its tail is connected to the second node.

Example 2:

Input: head = [1,2], pos = 0
 Output: tail connects to node index 0
 Explanation: there is a ring in the linked list, and its tail is connected to the first node.

Example 3:

Input: head = [1], pos = -1
 Output: no cycle
 Explanation: there are no links in the linked list.

Advanced:

  • Can you solve this problem without extra space?

Topics used:

Source: LeetCode
Link: https://leetcode-cn.com/problems/linked-list-cycle-lcci
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Topic realization

class Solution {
    public ListNode detectCycle(ListNode head) {
        if (head == null) return null;
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
                // The next time head and slow meet is the starting point of the ring
                while (head != slow) {
                    head = head.next;
                    slow = slow.next;
                }
                return slow;
            }
        }
        return null;
    }
}