JZ14 链表中倒数第k个结点

题目描述

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

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
     public ListNode FindKthToTail(ListNode head,int k) {
        
        ListNode tempNode = head;
        int count = 0;
        int i = 0;
        while (tempNode != null){
            count++;
            tempNode = tempNode.next;
        }
        if (k > count) {
            return null;
        }
        i = count - k;
        for (int j = 0; j < i; j++) {
            head = head.next;
        }
        return head;

    }
}

在这里插入图片描述

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
     public ListNode FindKthToTail(ListNode head,int k) {
        if (k <= 0 || head == null) {
            return null;
        }

        ListNode fast = head;
        ListNode slow = head;

        while (k > 0){
            if (fast == null) {
                return null;
            }
            fast = fast.next;
            k--;
        }
        while (fast != null){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;

    }
}

在这里插入图片描述

posted @ 2022-05-14 20:07  长勺  阅读(19)  评论(0)    收藏  举报