双指针-链表
链表中倒数第k个结点
http://www.nowcoder.com/questionTerminal/529d3ae5a407492994ad2a246518148a
/* 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; } int length = 1 ; ListNode temp = head; while(true){ if(temp.next == null){ break; } length++; temp = temp.next; } if(k > length){ return null; } int pos_k = length - k; ListNode temp1 = head; int pos_num = 0; while(pos_num < pos_k){ temp1 = temp1.next; pos_num++; } return temp1; } }
这道题是考链表的熟悉度,还是双指针的问题
抄的高赞的
public ListNode FindKthToTail(ListNode head,int k) { if(head == null || k ==0 ){ return null; } ListNode slow=head; ListNode fast=head; for(int i=0; i < k;i++){ if(fast == null){ return null; } fast = fast.next; } while(fast!=null){ slow=slow.next; fast=fast.next; } return slow; }