The title

Input a linked list, output the last KTH node of the list. In order to conform to the convention of most people, this case counts from 1, i.e. the last node of the list is the last node from the last.

For example, a linked list has six nodes, starting with the head node, whose values are 1, 2, 3, 4, 5, and 6. The third from last node of the list is the node with the value 4.

 

Example: Given a linked list: 1->2->3->4->5, and k = 2. Return to list 4->5.Copy the code

Their thinking

# 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: RNode = head lNode = None index = 0 while index! = k: rNode = rnode. next index += 1 lNode = head# When rNode is moved to the start of the gap k, lNode pointer starts moving while rNode! Next lNode = lnode. next return lNode if __name__ == '__main__': # # # #L1 1->2->3->4->5 # l1 = ListNode(1,ListNode(2, ListNode(3, ListNode(4, ListNode(5))))) # #L2 1->3->4 # l2 = ListNode(1, ListNode(3, ListNode(4))) list1 = [1, 2, 3, 4, 5, 6] nodeL1 = ListNode(0) headL1 = nodeL1 while len(list1) >0: node = ListNode(list1.pop()) nodeL1.next = node nodeL1 = node headL1 = headL1.next tempHeadL1 = headL1 while(tempHeadL1.next ! = None): # print(tempHeadL1.val) tempHeadL1 = tempHeadL1.next k = 2 ret = Solution().getKthFromEnd(headL1, k) while (ret ! = None): print(ret.val) ret = ret.nextCopy the code