Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to solve the problem of finding the last k node in leetcode linked list

Shulou Source: shulou.com Published: 2022-06-01 13:12:30 11月13日 Update

This article mainly introduces how to solve the problem of finding the last-to-last node of the leetcode linked list, which has a certain reference value, and interested friends can refer to it. I hope you can learn a lot after reading this article.

Enter a linked list and output the last-to-last node in the linked list. In order to meet the habits of most people, this topic starts counting from 1, that is, the end node of the linked list is the penultimate node. For example, a linked list has six nodes, starting from the top node, and their values are 1, 2, 3, 4, 5, and 6. The penultimate node of this linked list is the node with a value of 4. Example: given a linked list: 1-> 2-> 3-> 4-> 5, and k = 2. Return to linked list 4-> 5. Source: LeetCode link: https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof copyright belongs to the collar buckle network. For commercial reprint, please contact official authorization. For non-commercial reprint, please indicate the source. Answer the question / Definition for singly-linked list. * public class ListNode {* int val; * ListNode next; * ListNode (int x) {val = x;} *} * / class Solution {public ListNode getKthFromEnd (ListNode head, int k) {ListNode C1 = head; while (C1! = null & & k > 0) {C1 = c1.nextKmurf;} ListNode c2 = head While (C1! = null) {C1 = c1.next; c2 = c2.next;} return c2;}}

Fast and slow pointer, first let the fast pointer take k steps, and then the two pointers go synchronously. When the fast pointer reaches the end, the slow pointer is the last-to-last node of the linked list.

Thank you for reading this article carefully. I hope the article "how to solve the problem of finding the last-to-last node of the leetcode linked list" shared by the editor will be helpful to everyone. At the same time, I hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Tags: Nodes pointers articles questions two from scratch value interest provenance at the same time business official that is speed more friends this topic sources knowledge examples Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux MySQL Shulou Technology Microsoft Xiaomi