阿里面試題(1)反轉(zhuǎn)鏈表

題目信息

問題:如何實現(xiàn)一個高效的單向鏈表逆序輸出?
出題人:阿里巴巴出題專家:昀龍/阿里云彈性人工智能負責人

代碼

分別用C語言和Java完成了該題目,題目在Leetcode上難度是簡單。

  1. C語言代碼采用的是遞歸法
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* reverseList(struct ListNode* head){
    // 特殊情況, 原樣返回
    if (head == NULL || head->next == NULL) {
        return head;
    }
    // 該題使用遞歸的方法
    // 找到最后一個節(jié)點,作為新的頭
    // 而其他的節(jié)點接受反轉(zhuǎn)

    // 找到倒數(shù)第二個節(jié)點和最后一個節(jié)點
    struct ListNode* curr = head;
    struct ListNode* lastNode;
    struct ListNode* lastSecondNode;
    while (curr != NULL) {
        // 最后一個節(jié)點
        if (curr->next == NULL) {
            lastNode = curr;
        }
        // 倒數(shù)第二個節(jié)點
        else if (curr->next->next == NULL) {
            lastSecondNode = curr;
        }
        curr = curr->next;
    }

    // 倒數(shù)第二個節(jié)點后面接 NULL, 作為最后一個節(jié)點
    lastSecondNode->next = NULL;
    // 遞歸部分 最后一個節(jié)點接上反轉(zhuǎn)
    lastNode->next = reverseList(head);
    return lastNode;
}

  1. Java語言代碼利用了棧結(jié)構(gòu)后進先出的特點實現(xiàn)了鏈表的反轉(zhuǎn)。
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        // 特殊情況
        if (head == null || head.next == null) {
            return head;
        }
        // 用棧來做這題
        Stack<ListNode> stack = new Stack<>();
        // 將所有節(jié)點壓入棧
        ListNode curr = head;
        while (curr != null) {
            stack.push(curr);
            curr = curr.next;
        }
        // 最后一個節(jié)點作為新的頭
        ListNode newHead = stack.peek();
        while (!stack.isEmpty()) {
            // 指針指向彈出的節(jié)點
            ListNode node = stack.pop();
            // 彈出后??樟?            if (stack.isEmpty()) {
                node.next = null;
            }
            else {
                node.next = stack.peek();
            } 
        }
        // 返回新的 head
        return newHead;
    }
}

總結(jié)

遞歸與棧結(jié)構(gòu)兩種的空間復(fù)雜度都比較低,但是時間復(fù)雜度很高。
網(wǎng)友們有更加好的方法,值得學(xué)習(xí)。

視頻教程

視頻教程

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容