LintCode - 鏈表倒數(shù)第n個(gè)節(jié)點(diǎn)(普通)

版權(quán)聲明:本文為博主原創(chuàng)文章,未經(jīng)博主允許不得轉(zhuǎn)載。

難度:容易
要求:

找到單鏈表倒數(shù)第n個(gè)節(jié)點(diǎn),保證鏈表中節(jié)點(diǎn)的最少數(shù)量為n

樣例

給出鏈表** 3->2->1->5->null**和n = 2,返回倒數(shù)第二個(gè)節(jié)點(diǎn)的值1.

思路
先翻轉(zhuǎn),再計(jì)算

/**
     * @param head: The first node of linked list.
     * @param n: An integer.
     * @return: Nth to last node of a singly linked list. 
     */
    ListNode nthToLast(ListNode head, int n) {
        if(head == null){
            return null;
        }
        
        head = reverse(head);
        int index = 1;
        while(head.next != null){
            if(index++ == n){
                break;
            }
            head = head.next;
        }
        return head;
    }
    
    /**
     * 原地翻轉(zhuǎn)
     */
    private ListNode reverse(ListNode head){
        ListNode prev = null;
        while(head != null){
            ListNode tmp = head.next;
            head.next = prev;
            prev = head;
            head = tmp;
        }
        return prev;
    }

思路
雙指針,第一個(gè)指針先走n個(gè),然后第一個(gè)指針和第二個(gè)指針同時(shí)往右遍歷,當(dāng)?shù)谝粋€(gè)指針為null時(shí),第二個(gè)指針就為倒數(shù)第n個(gè)元素

/**
     * @param head: The first node of linked list.
     * @param n: An integer.
     * @return: Nth to last node of a singly linked list. 
     */
    ListNode nthToLast(ListNode head, int n) {
        if(head == null){
            return null;
        }
        
        ListNode dummy = head;

        for(int i = 0; i < n; i++){
            if(head == null){
                return null;
            }
            head = head.next;
        }
        
        ListNode pre = dummy;
        while(head != null){
            head = head.next;
            pre = pre.next;
        }
        
        return pre;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容