面试题15:链表中倒数第K个结点
输入一个链表,输出该链表中倒数第k个结点。
方法1:
这个解法要循环两次链表
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution1 { public ListNode FindKthToTail(ListNode list,int k) { if (list == null) return list; ListNode node = list; int count = 0; while (node != null) { count++; node = node.next; } if (count < k) return null; ListNode p = list;
//走n-k步 for (int i = 0; i < count - k; i++) { p = p.next; } return p; } }
方法2:快慢指针
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode FindKthToTail(ListNode head,int k) { if(head==null || k==0){ return null; } ListNode slow = head; ListNode fast = head; //fast指针先走k-1步 for (int i=0;i<k-1;i++){ if(fast.next==null){ return null; }else { fast = fast.next; } } while (fast.next!=null){ fast=fast.next; slow=slow.next; } return slow; } }
可以参考单链表成环 https://www.cnblogs.com/chengpeng15/p/9868109.html