zoukankan      html  css  js  c++  java
  • [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;
        }
    };
  • 相关阅读:
    Construction构造函数
    映射验证
    映射设置
    条件映射
    映射前和映射后的操作
    AutoMapper 5.0-升级指南
    Bootstrap Tree View
    MiniProfiler使用笔记
    关于添加数据自定义编号格式问题
    【Postgresql】数据库函数
  • 原文地址:https://www.cnblogs.com/simplepaul/p/11312418.html
Copyright © 2011-2022 走看看