Java in place O(n) solution: consider the linkedList as three parts

  • 0

    The basic thought about this solution is to split the linkedlist into three sub linkedlists while knowing that each part could be empty.
    Key points:

    1. The number of item in the range (n,m) is n+m+1.

    2. A dummy head was created to facilitate the tracking of the current head since the initial head might get reversed.

    3. The purpose of the first While loop was to nail down the first part.

    4. The second while loop was the code actually do the reverse. Two references/pointers were used to track the head and tail of the second part.

    5. The rest of the linked list is the third part.

      public class Solution {
      public ListNode reverseBetween(ListNode head, int m, int n) {
      if(m==n || head == null || == null) return head;
      int k = n-m+1;
      ListNode dummyHead,lastTail, reverseHead, reverseTail, temphead;
      reverseTail = null; reverseHead = null; temphead= null;
      dummyHead = new ListNode(0); = head;
      lastTail = dummyHead;
      lastTail = head;
      head =;
      //start reversing
      temphead = head;
      head =;
      if(reverseTail==null) {
      reverseHead = temphead;
      reverseTail = temphead;
      }else{ = reverseTail;
      reverseTail = temphead;
      //link three parts together
      if(reverseTail!=null) = reverseTail;
      if(reverseHead!=null) = head;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.