Fourteenth offer to prove safety problems: the list penultimate k nodes

Input a linked list, the linked list output reciprocal k-th node.

Ideas: the use of two pointers refer to a node on another head node in the k-means, so that the two circulating pointer while moving backward pointer points to a linked list until the tail pointer is the answer in the preceding

Code:

 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         if(k==0)
13             return null;
14         if(head==null)
15             return null;
16         else{
17             ListNode pre = head;
18             ListNode end = head;
19             for(int i=k-1;i>0;i--){
20                 end = end.next;
21             }
22             if(end==null)
23                 return null;
24             else if(end.next==null)
25                 return pre;
26             else{
27                 while(end.next!=null){
28                     pre = pre.next;
29                     end = end.next;
30                 }
31                 return pre;
32             }
33         }
34     }
35 }

Little lazy. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Guess you like

Origin www.cnblogs.com/haq123/p/12117184.html