• [Leetcode] Reverse Linked List II


    Reverse Linked List II 题解

    题目来源:https://leetcode.com/problems/reverse-linked-list-ii/description/


    Description

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

    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 ≤ m ≤ n ≤ length of list.

    Solution

    
    class Solution {
    public:
        ListNode* reverseBetween(ListNode* head, int m, int n) {
            if (head == NULL || head -> next == NULL || m == n)
                return head;
            ListNode *tempHead = new ListNode(0);
            tempHead -> next = head;
            ListNode *preNode = tempHead, *frontNode = head;
            int pos = 1;
            while (pos < m) {
                preNode = frontNode;
                frontNode = frontNode -> next;
                pos++;
            }
            ListNode *backNode = frontNode -> next;
            ListNode *nextNode = backNode -> next;
            while (pos < n) {
                backNode -> next = frontNode;
                frontNode = backNode;
                backNode = nextNode;
                if (nextNode == NULL) {
                    break;
                }
                nextNode = nextNode -> next;
                pos++;
            }
            preNode -> next -> next = backNode;
            preNode -> next = frontNode;
            return tempHead -> next;
        }
    };
    
    

    解题描述

    这道题题意是给出一个链表,要求将其中第m~n个节点进行反转。考虑的办法还是跟反转整个链表差不多,但是要考虑多一点是,要保存m-1位前的链表位置(即preNode)以及n+1位后的链表位置(即backNode),以便后续连接成新的链表。而当m = 1的时候,preNode处没有节点,考虑到这个情况,解法中加入了一个临时链表头tempHead以保证preNode的存在并且便于后续直接获取新的链表头即tempHead -> next

  • 相关阅读:
    docker部署springboot应用
    docker部署vue前端
    docker安装mysql5.7 数据挂载
    docker 部署nestjs应用
    unbuntu16.04安装geoserver运行环境
    windows server2012 搭建.netcore+nginx+nssm运行环境
    nginx部署多个网站
    vscode搭建springboot开发环境
    软工课程总结
    Beta答辩总结
  • 原文地址:https://www.cnblogs.com/yanhewu/p/8377391.html
Copyright © 2020-2023  润新知