链表中倒数第k个结点 java

版权声明:博客内容为本人自己所写,请勿转载。 https://blog.csdn.net/weixin_42805929/article/details/82990091

链表中倒数第k个结点 java

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

解析:
最佳代码:Java代码,通过校验。代码思路如下:两个指针,先让第一个指针和第二个指针都指向头结点,然后再让第一个指正走(k-1)步,到达第k个节点。然后两个指针同时往后移动,当第一个结点到达末尾的时候,第二个结点所在位置就是倒数第k个节点了。。

代码1:

/*
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(head == null){
            return null;
        }
        ListNode node = head;
        int count = 0;
        while(node != null){
            count++;
            node = node.next;
        }
        if(count < k){
            return null;
        }
        ListNode p = head;
        for(int i = 0; i < count - k; i++){
            p = p.next;
        }
        return p;
    }
}

代码2:推荐

public class Solution {
    public ListNode FindKthToTail(ListNode head, int k) {
        if(head == null || k <= 0){
            return null;
        }
        ListNode start = head;
        ListNode end = head;
        for(int i = 1; i < k; i++){
            if(start.next != null){
                start = start.next;
            }else{
                return null;
            }
        }
        while(start.next != null){
            start = start.next;
            end = end.next;
        }
        return end;
    }
}

代码3:

public class Solution {
    public ListNode FindKthToTail(ListNode head, int k) {
        if(head == null || k <= 0){
            return null;
        }
        ListNode start = head;
        ListNode end = head;
        for(int i = 1; i < k; i++){
            if(start.next != null){
                start = start.next;
            }else{
                return null;
            }
        }
        for(int i = k; start.next != null; i++){
            start = start.next;
            end = end.next;
        }
        return end;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42805929/article/details/82990091