zoukankan      html  css  js  c++  java
  • 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.

    A是A出来了,不过写的略挫,有点懒,不太想改了

     1 public class Solution {
     2     public ListNode reverseBetween(ListNode head, int m, int n) {      
     3         ListNode headNode = new ListNode(0);
     4         headNode.next = head;
     5         head = headNode;                            //插入一个头结点
     6         
     7         ListNode toEnd = head;
     8         ListNode toInsert = head;
     9         
    10         for(int i = 1; i < m; i++){                        //找到插入点
    11             toInsert = toInsert.next;
    12             toEnd = toEnd.next;
    13         }//for
    14         if(m < n){                                        //第一个采用头结点插入法插入的
    15             toEnd = toEnd.next;
    16             ListNode temp = new ListNode(toEnd.val);
    17             toInsert.next = temp;
    18         }//if
    19         
    20         int count = n - m;
    21         while(count > 0){                                //采用头插法
    22             toEnd = toEnd.next;
    23             ListNode temp = new ListNode(toEnd.val);
    24             temp.next = toInsert.next;
    25             toInsert.next = temp;
    26             count--;
    27         }//while
    28         
    29         if(m < n)
    30         {
    31             while(toInsert.next != null)
    32                 toInsert = toInsert.next;
    33             toInsert.next = toEnd.next;
    34         }
    35         
    36         head = head.next;
    37         return head;
    38     }    
    39 }
  • 相关阅读:
    ==与is区别
    词典操作
    前端工具---取色截图测量
    css零碎合集
    基于bootstrap的在线布局工具
    js常用功能工具库--Underscore.js
    前端资源荟萃
    在线绘图工具---processon
    表单form浅谈
    前端工具----iconfont
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4203580.html
Copyright © 2011-2022 走看看