【牛客网-名企高频面试题】NC 69 链表中倒数第k个结点

NC 69 链表中倒数第k个结点

题目描述:

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

示例1

输入

1,{1,2,3,4,5}

返回值

{5}

解题思路

方法一: 双指针解法

第一个指针先走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) {
        if(head == null || k == 0){
            return null;
        }
        ListNode slow = head;
        ListNode fast = head;
        for(int i = 0;i<k;i++){
            if(fast == null){
                return null;
            }
            fast = fast.next;
        }
        while(fast != null){
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }
}

方法二:先计算节点数n,再取第n-k个节点

    public ListNode FindKthToTail_1 (ListNode pHead, int k) {
        // write code here

        ListNode res = pHead;
        int count = 0;
        while(pHead != null){
            pHead = pHead.next;
            count++;
        }
        if(count < k) return null;
        for(int i = 0;i < count - k;i++){
            res = res.next;
        }
        return res;
    }
posted @ 2020-12-29 22:23  your_棒棒糖  阅读(71)  评论(0)    收藏  举报