Sword Pointer Offer (Special Assault Edition) Question 25|26

Preface

  • Now that the front-end requirements have become higher, you may encounter algorithm questions when looking for a job. Be prepared by brushing up on a few algorithm questions every day. Today is question 25|26 of "Sword Finger Offer (Special Assault Edition)".

Sword Points Offer II 025. Adding two numbers in a linked list

Given two non-empty linked lists l1 and l2 to represent two non-negative integers. The highest digit of the number is at the beginning of the linked list. Each of their nodes stores only one digit. Adding these two numbers returns a new linked list.

You can assume that except for the number 0, neither number will start with zero.

Difficulty: Moderate

Example 1:

Input: l1 = [7,2,4,3], l2 = [5,6,4] Output: [7,8,0,7]

Example 2:

Input: l1 = [2,4,3], l2 = [5,6,4] Output: [8,0,7]

Example 3:

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

hint:

  • The length range of the linked list is [1, 100]

  • 0 <= node.val <= 9

  • Input data ensures that the numbers represented by the linked list do not have leading 0s

Knowledge points: **Stack**[1] **Linked List**[2] **Mathematics**[3]

Method one: stack

Reverse the linked list representing integers. The head node of the reversed linked list represents the single digit, and the tail node represents the highest digit. At this time, adding from the head nodes of the two linked lists is equivalent to adding from the single digits of the integers.

What you also need to pay attention to when doing addition is carry. If the sum of the units digits of two integers exceeds 10, a carry is generated to the tens digit. This carry must be taken into account when adding tens digits in the next step.

step:

  1. Iterate the values ​​​​of the two linked lists into two stacks;

  2. Use two stacks to calculate the value of each bit and determine whether there is a carry;

  3. Construct a linked list using head interpolation;

 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */

 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
    let stack1 = [];
    let stack2 = [];

    
    while (l1 !== null) {
        stack1.push(l1.val);
        l1 = l1.next;
    }
    while (l2 !== null) {
        stack2.push(l2.val);
        l2 = l2.next;
    }

    let curr = null;
    let addOne = 0;

    while (addOne || stack1.length || stack2.length) {
        let val1 = stack1.length ? stack1.pop() : 0;
        let val2 = stack2.length ? stack2.pop() : 0;

        let sum = val1 + val2 + addOne;
        sum >= 10 ? addOne = 1 : addOne = 0;

        
        let currNode = new ListNode(sum % 10, curr);
        curr = currNode;
    }

    return curr;
};

Complexity analysis

  • Time complexity: O(max⁡(m,n)), where m and n are the lengths of the two linked lists respectively. We need to traverse all positions of the two linked lists, and processing each position only takes O(1) time.

  • Space complexity: O(m+n), where m and n are the lengths of the two linked lists respectively. The space complexity mainly depends on the space we use to put the contents of the linked list on the stack.

Sword Points Offer II 026. Rearrange the linked list

Given the head node head of a singly linked list L, the singly linked list L is expressed as:

L0 → L1 → … → Ln-1 → Ln
Please rearrange it to become:

L0 → Ln → L1 → Ln-1 → L2 → Ln-2 →

You can't just change the value inside the node, but you need to actually exchange the node.

Difficulty: Moderate

Example 1:

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

Example 2:

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

hint:

  • The length range of the linked list is [1, 5 * 104]

  • 1 <= node.val <= 1000

Knowledge points: **Stack**[4] **Recursion**[5] **Linked list**[6] **Double pointer**[7]

Method 1: Midpoint of linked list + Reverse order of linked list + Merge linked list

First, divide the linked list into two halves. In the figure above, the first half of the linked list contains 3 nodes 1, 2, and 3, and the second half of the linked list contains 3 nodes 4, 5, and 6.

Then reverse the second half of the linked list. After the second half of the example linked list is reversed, the order of the nodes becomes 6, 5, and 4.

Finally, starting from the head nodes of the first half of the linked list and the second half of the linked list, connect their nodes one by one to form a new linked list. First connect the head nodes 1 and 6 of the first half of the linked list and the second half of the linked list, then connect the nodes 2 and 5 at the second position, and finally connect the two tail nodes 3 and 4, so in the new The order of the nodes in the linked list is 1, 6, 2, 5, 3, 4.

The problem that needs to be solved is how to split a linked list into two halves. If the middle node of the linked list can be found, then the linked list can be divided into two halves based on the middle node. The first half of the linked list is located before the middle node, and the second half of the linked list is located after the middle node. You can use double nodes to find the middle node of the linked list. If two pointers, one fast and one slow, start from the head node of the linked list at the same time, the fast pointer moves forward two steps at a time along the next pointer, and the slow pointer only moves one step at a time, then when the fast pointer reaches the end node of the linked list The slow pointer has just reached the middle node of the linked list. It is worth noting that the total number of nodes in the linked list may be an odd number or an even number. When the total number of nodes in the linked list is an odd number, make sure that the first half of the linked list has one more node than the second half.

 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */

 * @param {ListNode} head
 * @return {void} Do not return anything, modify head in-place instead.
 */
var reorderList = function(head) {
  let dummy = new ListNode(0);
  dummy.next = head;
  let fast = dummy, slow = dummy;
  while (fast && fast.next) {
    slow = slow.next;
    fast = fast.next;
    if (fast.next) {
      fast = fast.next;
    }
  }
  
  let temp = slow.next;
  slow.next = null;
  
  link(head, reverseList(temp), dummy);
};

var reverseList = function(head) {
    if (!head) {
        return null;
    }
    let pre = null;
    let cur = head;
    while (cur) {
        const next = cur.next;
        cur.next = pre;
        pre = cur;
        cur = next;
    }
    return pre;
};

var link = function(node1, node2, head) {
    let prev = head;
    while (node1 && node2) {
      let temp = node1.next;
      prev.next = node1;
      node1.next = node2;
      prev = node2;
      node1 = temp;
      node2 = node2.next;
    }
    if (node1) {
      prev.next = node1;
    }
}

Complexity analysis

  • Time complexity: O(N), where N is the number of nodes in the linked list.

  • Space complexity: O(1).

so

  • The ending is still the same: there will be times when the wind and waves break, and the clouds and sails will sail directly to the sea!

  • The online collection is indeed very good. I have summarized and organized the articles, online preparation guide for interviews and question answering. You can take it away without any thanks. You must learn to stand on the shoulders of others and improve yourself. Click here --> 

at last:

If you are looking for a job now, you can send a private message to "web" or directly add an assistant to the group to receive the front-end interview brochure, resume optimization and modification, internal recommendations from major manufacturers , and more collections of real interview questions from Alibaba, Byte and major manufacturers , and p8 bosses Communicate together.

Guess you like

Origin blog.csdn.net/Likestarr/article/details/135360504