难度

  • 简单
  • 中等
  • [ ] 困难

    标签

    链表、双指针

    题目描述

    实现一种算法,找出单向链表中倒数第 k 个节点。返回该节点的值。

    示例1:

    1. 输入: 1->2->3->4->5 k = 2
    2. 输出: 4

    给定的k保证是有效的

    题解

    1. 两次遍历

    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. * int val;
    5. * ListNode next;
    6. * ListNode(int x) { val = x; }
    7. * }
    8. */
    9. class Solution {
    10. public int kthToLast(ListNode head, int k) {
    11. ListNode cur = head;
    12. int count = 1;
    13. while(cur.next != null) {
    14. cur = cur.next;
    15. count++;
    16. }
    17. int index = count - k + 1;
    18. ListNode result = head;
    19. while(--index > 0) {
    20. result = result.next;
    21. }
    22. return result.val;
    23. }
    24. }

2. 双指针

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public int kthToLast(ListNode head, int k) {
  11. ListNode first = head;
  12. int x = k;
  13. while(--x > 0) {
  14. first = first.next;
  15. }
  16. ListNode result = head;
  17. while(first.next != null) {
  18. first = first.next;
  19. result = result.next;
  20. }
  21. return result.val;
  22. }
  23. }