Live2D

链表中倒数第K个节点(Java)

/*
      输入一个链表,输出该链表中倒数第k个结点。
      输入
      复制
      1,{1,2,3,4,5}
      返回值
      复制
      {5}
*/
public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        if(head==null){
            return null;
        }
        ListNode node = head;
        if(node.next==null){
            return node;
        }
        int length = 0;
        while(node!=null){
            node = node.next;
            length++;
        }
        if(k>length){
            return null;
        }
        int count = 0;
        for(int i = 0;i<length-k;i++){
            head = head.next;
        }
        return head;
        
    }
}
posted @ 2021-01-19 15:49  细雪之舞0213  阅读(88)  评论(0)    收藏  举报