• 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->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.

    Analysis:

    We need three pointers: pre, cur and nextCur. This is because when we reverse cur.next to pre, we lose the link between cur and cur.next, then we cannot go on. We need record the node after cur also.

    We also need to address the case that m==1 carefully. In this case, the head of the list is changed.

    Solution:

     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         if (head==null) return head;
    15         if (m==n) return head;
    16         
    17         ListNode reHead = null;
    18         ListNode reHeadPre = null;
    19         ListNode cur=null;
    20         ListNode pre = null;
    21         int index = 1;
    22         cur = head;
    23         while (index!=m){
    24             pre = cur;
    25             cur = cur.next;
    26             index++;
    27         }
    28         
    29         reHead = cur;
    30         reHeadPre = pre;
    31         ListNode nextCur = cur.next;
    32         
    33         while (index!=n){
    34             pre = cur;
    35             //NOTE: it is not "cur = cur.next;", because the cur.next has been changed to pre!
    36             cur = nextCur;
    37             nextCur = nextCur.next;
    38             index++;
    39             cur.next = pre;
    40         }
    41         
    42         //Address the case that m==1.
    43         if (reHeadPre==null)
    44             head = cur;
    45         else 
    46             reHeadPre.next=cur;
    47         reHead.next=nextCur;
    48         
    49         return head;
    50     }
    51 }
  • 相关阅读:
    jQuery+ThinkPHP+Ajax实现即时消息提醒功能
    依赖注入(DI)
    控制反转(IoC)
    ajax以base64上传图片到django
    python 多进程、多线程、协程
    python3 实现tcp/udp局域网通信
    同源策略与跨域访问
    nginx+uwsgi阿里云ubuntu服务器上简单部署flask RESTful风格项目
    python3 实现 websocket server 解决中文乱码
    python IO 多路复用 epoll简单模型
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4100951.html
Copyright © 2020-2023  润新知