输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。
例如,一个链表有6个节点,从头节点开始,它们的值依次是1、2、3、4、5、6。这个链表的倒数第3个节点是值为4的节点。
示例:
给定一个链表: 1->2->3->4->5, 和 k = 2.
返回链表 4->5.
方法一:两次遍历
class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public class Solution { public static void main(String[] args) { ListNode head = new ListNode(2); Solution solution = new Solution(); ListNode kthFromEnd = solution.getKthFromEnd(head, 1); System.out.println(kthFromEnd.val); } public ListNode getKthFromEnd(ListNode head, int k) { int Len = 0; ListNode point = head; while (point != null) { Len += 1; point = point.next; } point = head; System.out.println("Len:" + Len); for (int i = 0; i < Len - k; i++) { point = point.next; } return point; } }
方法二:双指针法
class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public class Solution { public static void main(String[] args) { ListNode head = new ListNode(2); Solution solution = new Solution(); ListNode kthFromEnd = solution.getKthFromEnd(head, 1); System.out.println(kthFromEnd.val); } public ListNode getKthFromEnd(ListNode head, int k) { ListNode start = head, end = head; for (int i = 0; i < k; i++) { end = end.next; } while (end != null) { end = end.next; start = start.next; } return start; } }