zoukankan      html  css  js  c++  java
  • 30 Day Challenge Day 6 | Leetcode 92. Reverse Linked List II

    题解

    基于 Reverse Linked List 的同样思路,稍加修改,即可。但代码不够简洁,看上去过程也有些冗余。

    class Solution {
    public:
        ListNode* reverseBetween(ListNode* head, int m, int n) {
            ListNode* prev = nullptr;
            ListNode* curr = head;
            
            while(--m) {
                prev = curr;
                curr = curr->next;
                n--;
            }
            
            ListNode *p = prev, *q = curr;
            
            prev = curr;
            curr = curr->next;
            n--;
    
            while(curr && n--) {
                ListNode* temp = curr->next;
                curr->next = prev;
                prev = curr;
                curr = temp;
            }
            
            if(p) {
                p->next = prev;
                q->next = curr;
                return head; 
            }
    
            q->next = curr;
            return prev;
        }
    };
    

    稍加改进:用一个虚拟节点作为新的头节点。可以使得结尾的处理更简洁。

    class Solution {
    public:
        ListNode* reverseBetween(ListNode* head, int m, int n) {
            ListNode *dummy = new ListNode(0);        
            dummy->next = head;
    
            ListNode* curr = dummy;
            
            while(--m) {
                curr = curr->next;
                n--;
            }
            
            ListNode *p = curr, *q = curr->next;
            
            ListNode* prev = curr;
            curr = curr->next;
    
            while(curr && n--) {
                ListNode* temp = curr->next;
                curr->next = prev;
                prev = curr;
                curr = temp;
            }
    
            p->next = prev;
            q->next = curr;
            return dummy->next;
        }
    };
    
  • 相关阅读:
    个人作业——软件产品案例分析
    软件工程结对作业二
    软件工程团队展示
    软件工程第三次作业
    软件工程实践第二次作业
    软件工程实践第一次作业
    第八次课程作业
    第五次课程作业
    第四次课程作业
    wind本地MySQL数据到hive的指定路径
  • 原文地址:https://www.cnblogs.com/casperwin/p/13636759.html
Copyright © 2011-2022 走看看