zoukankan      html  css  js  c++  java
  • 【leetcode刷题笔记】Reverse Linked List II

    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->NULLm = 2 and n = 4,

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

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


    题解:

    如上图所示,几个重要的变量:

    prev记录m位置前一个位置上的ListNode,当完成2~5这一段的反转后,prev的next指针要设置成反转后的序列的第一个指针;

    head记录要反转的子列表的第一个ListNode;

    kepeler记录要反转的子列表的最后一个ListNode;

    有一种特殊的情况如下图所示:

    当要反转的序列的第一个ListNode就是链表的头结点的时候,prev指针为空。这时候反转后的链表头节点变成上述kepeler所指向的节点,所以要在最后单独处理。

    代码中21~25行的循环找到prev和head的位置,27~31行的循环找到kepeler的位置,33~39行的for循环将链表制定范围的链表反转。41行进行判断:反转后序列的头节点是否变成要反转的列表的最后一个节点——kepeler,如果是,返回kepeler,否则返回之前保存的原链表头结点。

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public ListNode reverseBetween(ListNode head, int m, int n) {
    14         int HeadNodes = 0;
    15         ListNode answer = head;
    16         ListNode prev = null;
    17         
    18         if(head == null || m >= n)
    19             return answer;
    20         
    21         while(HeadNodes+1 < m){
    22             prev = head;
    23             head = head.next;
    24             HeadNodes++;
    25         }
    26             
    27         ListNode kepeler = head;
    28         while(HeadNodes+1 < n){
    29             kepeler = kepeler.next;
    30             HeadNodes++;
    31         }
    32         
    33         for(int i = 0;i < n-m;i++){
    34             ListNode temp = head.next;
    35             head.next = kepeler.next;
    36             kepeler.next = head;
    37             
    38             head = temp;
    39         }
    40         
    41         if(prev == null)
    42             return kepeler;
    43         else{
    44             prev.next = kepeler;
    45             return answer;
    46         }
    47     }
    48 }
  • 相关阅读:
    ubuntu系统下安装最新版的MySQL
    scp本地服务器和远程服务器拷贝文件
    linux设置环境变量
    PHP程序员玩转Linux系列-lnmp环境的搭建
    nginx与负载均衡
    Linux下vim的常用命令总结
    nginx与location规则
    ssh秘钥对免密码登陆
    ubuntu下安装php pdo扩展和导入数据库
    ArrayList的删除实现
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3851482.html
Copyright © 2011-2022 走看看