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:

    类似于[leetcode]Reverse Nodes in k-Group,将m~n区间的节点剪出来,然后reverse之后再插进去。

    代码略

    思路2:

    借鉴了同学的算法,一遍遍历一遍逆序,大致思路是栈操作。

    代码如下:

     1 public class Solution {
     2     public ListNode reverseBetween(ListNode head, int m, int n) {
     3         if(head == null || m==n) return head;
     4         ListNode hhead = new ListNode(0);
     5         hhead.next = head;
     6         ListNode pre = hhead;
     7         for(int i = 0 ; i < m - 1; i++){
     8             pre = pre.next;
     9         }
    10         ListNode start = pre.next;
    11         for(int i = 0; i < n - m; i++){
    12             ListNode post = start.next;
    13             start.next = post.next;
    14             post.next = pre.next;
    15             pre.next = post;
    16         }
    17         return hhead.next;
    18     }
    19 }
  • 相关阅读:
    oracle在没
    一天中时针和分钟重合的次数
    oracle的隐藏的东东
    左右小移动
    JS全选的操作
    JS定时器
    在文件中查找字符串
    表单原件
    div和span互换
    div和span的区别
  • 原文地址:https://www.cnblogs.com/huntfor/p/3859227.html
Copyright © 2011-2022 走看看