[LeetCode] 經(jīng)典 - ListNode 翻轉(zhuǎn)

在LeetCode里面有很多題是關(guān)于ListNode翻轉(zhuǎn)的。我們把核心的部分拿出來說,寫成一個模板。

模板介紹

public ListNode reverse(ListNode begin, ListNode end) {
    ListNode cur = begin.next;
    ListNode next;
    ListNode newTail = cur;
    ListNode pre = begin;
    while (cur != end) {
        next = cur.next;
        cur.next = pre;
        pre = cur;
        cur = next;
    }
    begin.next = pre;
    newTail.next = end;
    // return begin.next; // 如果想返回新的head
    return newTail; // 如果想返回翻轉(zhuǎn)后的的tail
}

LeetCode 26就是用了這個部分。

如果是翻轉(zhuǎn)整個List,end == null,那么我們這部分核心代碼可以變成:

public ListNode reverse(ListNode head) { // head是begin的next
    ListNode begin = new ListNode(-1);
    begin.next = head;
    ListNode cur = begin.next; 
    ListNode next;
    ListNode newTail = cur;
    ListNode pre = begin;
    while (cur != null) {
        next = cur.next;
        cur.next = pre;
        pre = cur;
        cur = next;
    }
    begin.next = pre;
    newTail.next = null;
    return begin.next; // 如果想返回新的head
}

或者簡練成:

public ListNode reverse(ListNode head) {
    ListNode pre = null;
    ListNode cur = head;
    while (cur != null) {
        ListNode next = cur.next;
        cur.next = pre;
        pre = cur;
        cur = next;
    }
    return pre;
}

相關(guān)題目

25 Reverse Nodes in k-Group
https://leetcode.com/problems/reverse-nodes-in-k-group/

206 Reverse Linked List
https://leetcode.com/problems/reverse-linked-list/

最后編輯于
?著作權(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)容