Sword finger off: the penultimate k-th node in the linked list

Title : Enter a linked list, the linked list output reciprocal k-th node, in order to comply with the habit of most people, this question starts counting from 1, i.e. the end of the node list is the inverse of the first node. For example, a linked list has 6 nodes, starting from the head node, their values ​​are 1, 2, 3, 4, 5, 6. The penultimate node of this linked list is a node with a value of 4.

Example : input 1-> 2-> 3-> 4-> 5 and k = 2; output: 4-> 5

Test site : Robustness of the code

Algorithm : 1. Initialization : front pointer former, rear pointer later; both pointers point to the head node

     2. Construct a dual pointer distance : the front pointer moves forward by k-1 steps.

     3. Double pointer movement : From the kth step, the two pointers move forward together until the former points to the tail node.

   4. Return value : just return later.

Time complexity O (N): N is the length of the linked list, the former moves forward by N-1 steps, and the latter moves forward by Nk steps.

Space complexity O (1): double pointer former, latter uses constant size space.

According to the above algorithm, we can write the following code:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
        former = latter = head
        for _ in range(k-1):
            former = former.next
        while former.next:
            latter, former = latter.next, former.next
        return latter

But the robustness of the above code is not enough, there are three problems:

  1. The linked list is empty. Because the code will access the memory pointed to by the null pointer, causing the program to crash
  2. The input parameter k = 0; will also cause the program to crash
  3. The number of nodes in the linked list is less than k. There is also the problem of accessing the memory pointed to by the null pointer and causing the program to crash;

Improve the code:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
        # 空链表
        if not head:
            return head
        # k = 0
        if k == 0:
            return None

        former = latter = head
        for _ in range(k-1):
            # k > 链表长度
            if former.next is not None:
                former = former.next
            else:
                return None
        while former.next:
            latter, former = latter.next, former.next
        return latter

 

Guess you like

Origin www.cnblogs.com/aniu-caili/p/12749957.html