面试题:链表倒数第k个节点

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

方法1:遍历两次链表

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

方法2:遍历一次链表(第一个指针提前走k-1步)

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

猜你喜欢

转载自www.cnblogs.com/Aaron12/p/9508279.html