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.

    [解题思路]

    添加一个safeguard,防止处理m=1的情况,用p1, p2, p3记录m-1, m, n这几个节点的引用

    当处理到m+1~n这些节点时将,将它们的next指向前一个节点

     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         // Start typing your Java solution below
    15         // DO NOT write main() function
    16         if(head == null || m == n){
    17             return head;
    18         }
    19         
    20         ListNode fake = new ListNode(Integer.MIN_VALUE);
    21         fake.next = head;
    22         head = fake;
    23         
    24         int count = 0;
    25         ListNode pre = null, p = head, p1 = null, p2 = null, p3 = null;
    26         while(count <= n){
    27             if(count == m - 1){
    28                 p1 = p;
    29             } else if(count == m){
    30                 p2 = p;
    31             } else if(count == n){
    32                 p3 = p;
    33             }
    34             ListNode tmp = p.next;
    35             if(count >= m + 1 && count <= n){
    36                 p.next = pre;
    37             }
    38             pre = p;
    39             p = tmp;
    40             count++;
    41         }
    42         p1.next = p3;
    43         p2.next = p;
    44         return head.next;
    45     }
    46 }
  • 相关阅读:
    支付宝H5支付---证书模式
    Redis分布式锁
    Docker+Nginx+Ssl
    Java调用函数传递参数到底是值传递还是引用传递
    Mysql索引查询失效的情况
    mysql索引之最左前缀法则
    数据的三大范式以及什么是反三大范式
    SpringMvc的工作流程
    Android 环境搭建
    Python 爬虫: 抓取花瓣网图片
  • 原文地址:https://www.cnblogs.com/feiling/p/3263501.html
Copyright © 2011-2022 走看看