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

public class TestList{
public ListNode FindKthToTail(ListNode head,int k) {
        if(head==null){
            return null;
        }
        int s=GetSize(head);
        if(k<0||k>s){
            return null;
        }
        ListNode cur=head;
        for(int i=0;i<s-k;i++){
            cur=cur.next;
        }return cur;
   }
   private int GetSize(ListNode head){
    int size=0;
    for(ListNode cur=head;cur!=null;cur=cur.next){
        size++;
    }
    return size;
   }

}
发布了87 篇原创文章 · 获赞 2 · 访问量 696

猜你喜欢

转载自blog.csdn.net/Nabandon/article/details/104086942