Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How does leetCode find the last-to-last node in the linked list

Shulou Source: shulou.com Published: 2022-06-01 13:03:16 09月26日 Update

Editor to share with you leetCode how to find the last-to-last node in the linked list, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

First, the last but one node 1 in the linked list, a brief description of the problem

Enter a linked list and output the last but one 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.

2. Example description example:

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

Return to linked list 4-> 5.

3, the train of thought of solving the problem

The problem can be solved by using fast and slow pointers.

4, problem solving procedure

Import java.util.ArrayList

Import java.util.LinkedList

Import java.util.List

Public class GetKthFromEndTest {

Public static void main (String [] args) {

ListNode L1 = new ListNode (1)

ListNode L2 = new ListNode (2)

ListNode L3 = new ListNode (3)

ListNode L4 = new ListNode (4)

ListNode L5 = new ListNode (5)

L1.next = L2

L2.next = L3

L3.next = L4

L4.next = L5

Int k = 2

ListNode listNode = getKthFromEnd (L1, k)

System.out.println ("listNode =" + listNode)

}

Public static ListNode getKthFromEnd (ListNode head, int k) {

If (head = = null | | head.next = = null) {

Return head

}

ListNode slow = head

ListNode fast = head

For (int I = 0; I < k; iTunes +) {

Fast = fast.next

}

While (fast! = null) {

Slow = slow.next

Fast = fast.next

}

Return slow

}

}

The above is all the content of the article "how to find the last k node in the linked list by leetCode". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Nodes articles content examples problem solutions not much from scratch most speed ideas pointers more knowledge procedures industry information information channels questions channels several people Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Linux Shulou Tech Info Xiaomi macOS