输入一个链表,输出该链表中倒数第k个结点。

//方案一code

public class Solution {io

public ListNode FindKthToTail(ListNode head,int k) {
    if(k==0)
        return null;
     ListNode pre=null;
     int i=0;
    
     while(head!=null){
        if(i%k==0)
            pre=head;
         head=head.next;
          i++;
     }
    
    if(i<k)
        return null;
    else
        return pre;
}

}class

//方案二:List

public class Solution {next

public ListNode FindKthToTail(ListNode head,int k) {
    if(head==null||k==0)
        return null;
    ListNode temp=head;
    
    for(int i=0;i<k-1;i++){
        if(head.next==null)
            return null;
        head=head.next;
    }
    
    while(head.next!=null){
        head=head.next;
        temp=temp.next;
    }
    
    return temp;
}

}时间

我的推荐用方案一:时间也短,空间也用的少一些while

相关文章
相关标签/搜索