Some people say that these linked list algorithms are very simple.

Keywords: less

1. The sum of two numbers

Title Description

Leetcode: Given two non-empty linked lists to represent two non-negative integers. Bits are stored in reverse order, and each of their nodes only stores a single number. Add the two numbers back to a new linked list.

You can assume that neither of these numbers will begin with zero except the number 0.

Example:

Input: (2 - > 4 - > 3) (5 - > 6 - > 4)
Output: 7 - > 0 - > 8
 Cause: 342 465 = 807

problem analysis

Leetcode Official Detailed Answer Address:

https://leetcode-cn.com/problems/add-two-numbers/solution/

To operate on the header node, consider creating dummy node, and use dummy - > next to represent the real header node. This avoids dealing with boundary problems where the head node is empty.

We use variables to track carry and start simulating the process of adding bits by bits from headers containing the lowest significant bits.

Solution

We start by adding the lowest significant bits, which are the headers of lists l1 and l2. Note the need to take into account the carry situation!

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
 //https://leetcode-cn.com/problems/add-two-numbers/description/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummyHead = new ListNode(0);
    ListNode p = l1, q = l2, curr = dummyHead;
    //Carry denotes carry digits
    int carry = 0;
    while (p != null || q != null) {
        int x = (p != null) ? p.val : 0;
        int y = (q != null) ? q.val : 0;
        int sum = carry   x   y;
        //Enter digit
        carry = sum / 10;
        //The value of the new node is sum% 10
        curr.next = new ListNode(sum % 10);
        curr = curr.next;
        if (p != null) p = p.next;
        if (q != null) q = q.next;
    }
    if (carry > 0) {
        curr.next = new ListNode(carry);
    }
    return dummyHead.next;
}
}

2. Flipping list

Title Description

Dagger offer: Input a list, invert the list, output all elements of the list.

problem analysis

This algorithmic problem, to be straightforward, is: how to make the latter node point to the former node! In the following code, a next node is defined, which mainly saves the node to reverse the head to prevent the list from "breaking".

Solution

public class ListNode {
  int val;
  ListNode next = null;

  ListNode(int val) {
    this.val = val;
  }
}

/**
 * 
 * @author Snailclimb
 * @date 2018 September 19th 2013
 * @Description: TODO
 */
public class Solution {

  public ListNode ReverseList(ListNode head) {

    ListNode next = null;
    ListNode pre = null;

    while (head != null) {
      // Save the node to reverse the head
      next = head.next;
      // The node to be inverted points to the previous node that has been inverted (Note: The first inversion points to null)
      head.next = pre;
      // The last node that has been reversed to the head
      pre = head;
      // Go straight to the end of the list
      head = next;
    }
    return pre;
  }

}

Test methods:

  public static void main(String[] args) {

    ListNode a = new ListNode(1);
    ListNode b = new ListNode(2);
    ListNode c = new ListNode(3);
    ListNode d = new ListNode(4);
    ListNode e = new ListNode(5);
    a.next = b;
    b.next = c;
    c.next = d;
    d.next = e;
    new Solution().ReverseList(a);
    while (e != null) {
      System.out.println(e.val);
      e = e.next;
    }
  }

Output:

5
4
3
2
1

3. The reciprocal k node in the list

Title Description

Sword finger offer: Input a list and output the reciprocal k node in the list.

problem analysis

The reciprocal k node in the list is also the positive (L-K 1) node, knowing only a little, this problem is basically no problem!

First, two nodes/pointers, one node node1 starts running, the pointer node1 runs to k-1 node, and the other node node2 starts running. When node1 runs to the end, the node referred to by node2 is the penultimate K node, that is, the positive (L-K 1) node.

Solution

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/

// Time complexity O(n), one traversal is enough.
// https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a?tpId=13&tqId=11167&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
public class Solution {
  public ListNode FindKthToTail(ListNode head, int k) {
    // If the list is empty or k is less than or equal to 0
    if (head == null || k <= 0) {
      return null;
    }
    // Declare two nodes pointing to the header node
    ListNode node1 = head, node2 = head;
    // Number of recording nodes
    int count = 0;
    // Record the k value, which you will use later
    int index = k;
    // The p pointer runs first and records the number of nodes. When the node 1 runs k-1, the node 2 runs.
    // When the node 1 runs to the end, the node 2 refers to the penultimate node.
    while (node1 != null) {
      node1 = node1.next;
      count  ;
      if (k < 1 && node1 != null) {
        node2 = node2.next;
      }
      k--;
    }
    // If the number of nodes is less than the required reciprocal k node, it returns null
    if (count < index)
      return null;
    return node2;

  }
}

4. Delete the penultimate N node of the list

Leetcode: Given a linked list, delete the reciprocal nth node of the linked list and return the head node of the linked list.

Example:

Given a list: 1 - > 2 - > 3 - > 4 - > 5, and n = 2.

When the penultimate node is deleted, the list becomes 1 - > 2 - > 3 - > 5.

Explain:

The given n guarantee is valid.

Advance:

Can you try a scan?

This question has a detailed answer on Leetcode, which can be referred to in detail.

problem analysis

We noticed that this problem can be easily simplified to another problem: delete the first (L - n 1) node from the beginning of the list, where L is the length of the list. As long as we find the length L of the list, this problem can be easily solved.

Solution

Twice ergodic method

First, we will add a dumb node as a supplement, which is located at the head of the list. Dummy nodes are used to simplify extreme situations, such as having only one node in a list, or deleting the head of a list. In the first traversal, we find the length L of the list. Then set a pointer to the dumb node and move it through the list until it reaches the (L - n) node. We link the next pointer of the node (L - n) to the node (L - n 2) to complete the algorithm.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
// https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/description/
public class Solution {
  public ListNode removeNthFromEnd(ListNode head, int n) {
    // Dumb nodes are used to simplify extreme situations, such as having only one node in a list or deleting the head of a list.
    ListNode dummy = new ListNode(0);
    // Dumb Node Pointing to Head Node
    dummy.next = head;
    // Save the length of the linked list
    int length = 0;
    ListNode len = head;
    while (len != null) {
      length  ;
      len = len.next;
    }
    length = length - n;
    ListNode target = dummy;
    // Find the node at L-n position
    while (length > 0) {
      target = target.next;
      length--;
    }
    // Relink the next pointer of the (L - n) node to the (L - n 2) node
    target.next = target.next.next;
    return dummy.next;
  }
}

Complexity analysis:

  • Time complexity O (L): The algorithm traverses the list twice, first calculates the length of the list LL, and then finds the (L - n)(L_n) nodes. The operation executes 2L-n2L_n steps with time complexity of O(L)O(L).
  • Spatial complexity O(1): We only use extra space of constant magnitude.

Advancement-one-time traversal method:

** The reciprocal N node in the list is also the positive (L-N 1) node.

In fact, this method is the same as the idea we used in Question 4 above to find the reciprocal k node in the list. The basic idea is to define two nodes: node 1 and node 2; node 1 runs first, node 1 runs to the n-first node, node 2 runs. When node 1 runs to the last node, node 2 is located at the (L-n) node (L stands for the total list length, that is, the penultimate n-1 node). Node)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
  public ListNode removeNthFromEnd(ListNode head, int n) {

    ListNode dummy = new ListNode(0);
    dummy.next = head;
    // Declare two nodes pointing to the header node
    ListNode node1 = dummy, node2 = dummy;

    // Node 1 runs first and Node 2 runs when Node 1 runs to Node n.
    // When node 1 runs to the last node, the location of node 2 is the (L-n) node, which is the penultimate n 1 (L represents the total list length).
    while (node1 != null) {
      node1 = node1.next;
      if (n < 1 && node1 != null) {
        node2 = node2.next;
      }
      n--;
    }

    node2.next = node2.next.next;

    return dummy.next;

  }
}

5. Merge two sorted linked lists

Title Description

Sword finger offer: Input two monotonically increasing linked lists, output two linked lists after the synthesis of the list, of course, we need to synthesize the list to meet the monotonic rule.

problem analysis

We can analyse in this way:

  1. Suppose we have two linked lists A and B.
  2. The value of A's head node A1 is compared with that of B's head node B1. Assuming A1 is small, A1 is the head node.
  3. A2 is compared with B1 again. Assuming B1 is small, A1 points to B1.
  4. Comparison of A2 and B2
    It's enough to go back and forth. It should be well understood.

Consider implementing it recursively!

Solution

Recursive version:

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
//https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337?tpId=13&tqId=11169&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
       if(list1 == null){
           return list2;
       }
       if(list2 == null){
           return list1;
       }
       if(list1.val <= list2.val){
           list1.next = Merge(list1.next, list2);
           return list1;
       }else{
           list2.next = Merge(list1, list2.next);
           return list2;
       }       
   }
}

Thank you for seeing it. If you can help me, please give me a compliment.

More experience and technology welcome to come to learn together: a little classroom - online learning platform for dreams http://www.yidiankt.com/

Students who want to study in depth can learn and discuss with more teachers on Wechat "Duoduo_laoshi". ~There is a full set of resources to share, experience to explore, wait for you!

Posted by baber_abbasi on Wed, 18 Sep 2019 21:38:37 -0700