zoukankan      html  css  js  c++  java
  • LeetCode Reverse Linked List II

    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.

     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) {
    15                 return null;
    16             }
    17             if(n==m){
    18                 return head;
    19             }
    20             ListNode temp=head,doRe = null,second=null,first=null,last=null;
    21             int i=1;
    22             
    23             while (temp!=null) {
    24                 if (i==m-1) {
    25                     first=temp;
    26                 }
    27                 if (i==m) {
    28                     doRe=temp;
    29                 }
    30                 if (i==n) {
    31                     last=temp;
    32                     second=temp.next;
    33                     if(first!=null) first.next=last;
    34                     last.next=null;
    35                     
    36                     break;
    37                 }
    38                 ++i;
    39                 temp=temp.next;
    40             }
    41             reverse(doRe);
    42             doRe.next=second;
    43             if (m>1) {
    44                 return head;
    45             }else {
    46                 return last;
    47             }
    48             
    49     }
    50     private void reverse(ListNode head) {
    51         ListNode pre = null,curr,next;
    52 
    53         curr=head;
    54         if (head==null) {
    55             return;
    56         }
    57         while (curr!=null) {
    58             next=curr.next;
    59             curr.next=pre;
    60             pre=curr;
    61             curr=next;
    62         }
    63     }
    64 }
  • 相关阅读:
    Confluence 6 在升级过程中查看合并日志
    Confluence 6 从 WIKI 标记整合到基于 XHTML 的存储格式
    Confluence 6 升级完成后的检查
    Confluence 6 超过当前许可证期限进行升级
    HDU2571--命运---DP
    HDU 2084 DP经典例子---数塔问题
    紫书第二章
    求组合数
    欧拉函数
    二分幂/快速幂
  • 原文地址:https://www.cnblogs.com/birdhack/p/4098366.html
Copyright © 2011-2022 走看看