【Lintcode】166. Nth to Last Node in List

題目地址:

https://www.lintcode.com/problem/nth-to-last-node-in-list/description

給定一個鏈表,求其倒數第nn個節點。題目保證nn是合法的。

快慢指針,快指針先走nn步然後慢指針快指針一起走。代碼如下:

public class Solution {
    /*
     * @param head: The first node of linked list.
     * @param n: An integer
     * @return: Nth to last node of a singly linked list.
     */
    public ListNode nthToLast(ListNode head, int n) {
        // write your code here
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        ListNode slow = dummy, fast = dummy;
        for (int i = 0; i < n; i++) {
            fast = fast.next;
        }
        
        while (fast != null) {
            slow = slow.next;
            fast = fast.next;
        }
        
        return slow;
    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
    }
}

時間複雜度O(l)O(l)ll爲鏈表長度,空間O(1)O(1)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章