题解 | #链表中倒数最后k个结点#
链表中倒数最后k个结点
http://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9
区间(长度为n)一起走直到遇到尾巴,则这个区间就是我们所需要的。
/* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { public ListNode FindKthToTail (ListNode pHead, int k) { if (pHead == null) { return null; } if (k == 0) { return null; } ListNode head = pHead; ListNode tail = pHead; int n = k; while(--n > 0) { if (tail.next == null) { return null; } tail = tail.next; } while(tail.next != null) { tail = tail.next; head = head.next; } ListNode newHead = new ListNode(head.val); ListNode newTail = newHead; while(head.next != null) { head = head.next; newTail.next = new ListNode(head.val); newTail = newTail.next; } return newHead; } }