面试题 02.02:返回倒数第 k 个节点

This commit is contained in:
huangge1199 2021-06-07 13:19:42 +08:00
parent ca377e5c18
commit eb3cf99dde
2 changed files with 67 additions and 0 deletions

View File

@ -0,0 +1,54 @@
//实现一种算法找出单向链表中倒数第 k 个节点返回该节点的值
//
// 注意本题相对原题稍作改动
//
// 示例
//
// 输入 1->2->3->4->5 k = 2
//输出 4
//
// 说明
//
// 给定的 k 保证是有效的
// Related Topics 链表 双指针
// 👍 72 👎 0
package leetcode.editor.cn;
import com.code.leet.entiy.ListNode;
//面试题 02.02:返回倒数第 k 个节点
public class KthNodeFromEndOfListLcci{
public static void main(String[] args) {
//测试代码
Solution solution = new KthNodeFromEndOfListLcci().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int kthToLast(ListNode head, int k) {
ListNode p;
int count = 1;
p = head;
while (p.next != null) {
count++;
p = p.next;
}
p = head;
for (int i = 0; i < count - k; i++) {
p = p.next;
}
return p.val;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,13 @@
<p>实现一种算法,找出单向链表中倒数第 k 个节点。返回该节点的值。</p>
<p><strong>注意:</strong>本题相对原题稍作改动</p>
<p><strong>示例:</strong></p>
<pre><strong>输入:</strong> 1-&gt;2-&gt;3-&gt;4-&gt;5 和 <em>k</em> = 2
<strong>输出: </strong>4</pre>
<p><strong>说明:</strong></p>
<p>给定的 <em>k</em>&nbsp;保证是有效的。</p>
<div><div>Related Topics</div><div><li>链表</li><li>双指针</li></div></div>\n<div><li>👍 72</li><li>👎 0</li></div>