• [LeetCode] 92. Reverse Linked List II


    Reverse a linked list from position m to n. Do it in one-pass.

    Note: 1 ≤ m ≤ n ≤ length of list.

    Example:

    Input: 1->2->3->4->5->NULL, m = 2, n = 4
    Output: 1->4->3->2->5->NULL

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* reverseBetween(ListNode* head, int m, int n) {
            // 建一个dummy node,连上原链表的头结点,这样的话就算头结点变动了,还可以通过dummy->next来获得新链表的头结点
            ListNode *dummy = new ListNode(-1), *pre = dummy;
            dummy->next = head;
            
            ListNode* cur = nullptr;
            for (int i = 0; i < m - 1; i++) {
                pre = pre -> next;
            }
            cur =  pre -> next;
            
            for (int i = m; i < n; i++) {
                ListNode *t = cur->next;
                cur -> next = t -> next;
                // 注意此处 pre 指针是不会变化的
                t -> next = pre -> next;
                pre -> next = t;
            }
            return dummy->next;
        }
    };
  • 相关阅读:
    移动布局---1. 移动端布局基础
    1. CSS新特性之选择器
    1. H5新增语义化标签
    POJ 3281
    poj 1986
    POJ 3728
    poj 2763
    poj 2749
    uva 11294
    LA 3713
  • 原文地址:https://www.cnblogs.com/simplepaul/p/11312418.html
Copyright © 2020-2023  润新知