题目描述
输入一个链表,输出该链表中倒数第k个结点。
1 /* 2 public class ListNode { 3 int val; 4 ListNode next = null; 5 6 ListNode(int val) { 7 this.val = val; 8 } 9 }*/ 10 public class Solution { 11 public ListNode FindKthToTail(ListNode head,int k) { 12 ListNode dummy = new ListNode(0); 13 if (k == 0) return null; 14 dummy.next = head; 15 ListNode p1 = dummy, p2 = dummy; 16 int i = 0; 17 while (p1.next != null && i < k - 1) { 18 p1 = p1.next; 19 i++; 20 } 21 if (p1.next == null) { 22 return null; 23 } 24 25 26 while (p1.next != null) { 27 p1 = p1.next; 28 p2 = p2.next; 29 } 30 return p2; 31 32 } 33 }