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 }
  • 相关阅读:
    增删改查
    兴趣爱好
    兴趣爱好界面
    购物商城
    计算器
    安卓第四周作业
    安卓第一周作业
    第十五周作业
    十三周作业-集合
    第十三周上机练习
  • 原文地址:https://www.cnblogs.com/huntfor/p/3859227.html
Copyright © 2011-2022 走看看