链表中倒数第k个节点(剑指offer-14)

 

 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 P2 = head;//head其实就是P1节点,让P2和P1指向链表开头
13         while(k != 0){
14             if(P2 == null){//k超出链表长度,直接返回null
15                 return null;
16             }
17             P2 = P2.next;
18             k--;
19         }
20         while(P2 != null){//同时移动P1和P2
21             P2 = P2.next;
22             head = head.next;
23         }
24         return head;
25     }
26 }

 

posted @ 2020-07-01 12:05  10000_Hours  阅读(67)  评论(0编辑  收藏  举报