zoukankan      html  css  js  c++  java
  • 92. Reverse Linked List II (List)

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

    For example:
    Given 1->2->3->4->5->NULL, m = 2 and n = 4,

    return 1->4->3->2->5->NULL.

    Note:
    Given m, n satisfy the following condition:
    1 ≤ mn ≤ length of list.

    /**
     * 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) {
            ListNode* fakeHead = new ListNode(0);
            fakeHead->next = head;
            
            //find the last element of first section
            ListNode* rHead = fakeHead;
            int i = 0;
            for(; i < m-1; i++){
                rHead = rHead->next;
            }
            
            //m-n element will be reversed
            ListNode* secondHead = rHead->next; //head of the original second section
            ListNode* current = secondHead->next; //current node to reverse
            ListNode* tmp;
            for(i = m; i < n; i++){ //reverse from m to n
                tmp = rHead->next;
                rHead->next = current;
                secondHead->next = current->next;
                current->next = tmp;
                current = secondHead->next;
            }
            
            //keep the third section and return
            return fakeHead->next;
    
        }
    };
  • 相关阅读:
    Spring
    Spring
    Spring
    Spring
    JS 脱敏通用方法
    JS 实用技巧记录
    多快?好省!
    实战 | 如何使用微搭低代码实现按条件过滤数据
    2021腾讯数字生态大会落地武汉,微搭低代码专场等你来
    实战 | 如何使用微信云托管部署flask项目
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4853123.html
Copyright © 2011-2022 走看看