题目:
输入一个链表,输出该链表倒数第k个节点。
解答:
1 public class Solution { 2 3 public static ListNode findKthToTail(ListNode pHead, int k) { 4 if(pHead == null || k == 0) { 5 return null; 6 } 7 8 ListNode pAhead = pHead; 9 ListNode pBehind = null; 10 for(int i = 0; i < k; i++) { 11 if(pAhead.next != null) { 12 pAhead = pAhead.next; 13 } else { 14 return null; 15 } 16 } 17 18 pBehind = pHead; 19 while(pAhead.next != null) { 20 pAhead = pAhead.next; 21 pBehind = pHead.next; 22 } 23 24 return pBehind; 25 } 26 }