zoukankan      html  css  js  c++  java
  • [leetcode]Reverse Linked List II

    = =简单题...

    尝试考虑了各种情况...

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *reverse(ListNode* start){
            ListNode* prev = nullptr;
            ListNode* now = start;
            while(now != nullptr){
                ListNode* next = now -> next;
                now -> next = prev;
                prev = now;
                now = next;
            }
            return prev;
        }
        ListNode *reverseBetween(ListNode *head, int m, int n) {
            if(m == n) return head;
            if(head == nullptr) return head;
            
            int cnt = 1;
            ListNode* prev = nullptr;
            ListNode* breakNode = head;
            // m is head
            while(cnt < m){
                prev = breakNode;
                breakNode = breakNode -> next;
                cnt ++;
            }
            ListNode* last = breakNode;
            cnt = n - m; // pre of last
            //last is tail
            while(cnt > 0){
                last = last -> next;
                cnt --;
            }
            //do reverse
            ListNode* next = last -> next;
            last -> next = nullptr;
            ListNode * newList = reverse(breakNode);
            if(prev){
                prev -> next = newList;
            }else{
                head = newList;
            }
            breakNode -> next = next;
            return head;
        }
    };
  • 相关阅读:
    前端布局定位
    CSS优化
    CSS工程化
    CSS过渡,动画,2D,3D转换
    CSS,盒子和美化技巧
    HTMl
    定位和布局
    CSS选择器
    八. 实时更新插件 livereload
    七. 浏览器插件 View in Browser
  • 原文地址:https://www.cnblogs.com/x1957/p/3510077.html
Copyright © 2011-2022 走看看