《剑指offer》14.链表中倒数第k个结点

题目地址:https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a?tpId=13&tqId=11167&rp=4&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

解题思路:两个指针,第一个指针先走k-1步,然后两个指针一起往后走,当第一个指针达到末尾的时候,第二个指针的位置就是倒数第k个节点。时间复杂度为O(n),空间复杂度为O(1).

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

猜你喜欢

转载自blog.csdn.net/qq_28900249/article/details/89295554