Advertisement
1988coder

92. Reverse Linked List II

Jan 13th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.55 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/reverse-linked-list-ii/
  2.  
  3. //   Definition for singly-linked list.
  4. // class ListNode {
  5. //     int val;
  6. //     ListNode next;
  7.  
  8. //     ListNode(int x) {
  9. //         val = x;
  10. //     }
  11. // }
  12.  
  13. /**
  14.  * One Pass Solution
  15.  *
  16.  * Time Complexity: O(min(L, n))
  17.  *
  18.  * Space Complexity: O(1)
  19.  *
  20.  * L = Length of the list (Total Number of nodes). n = input index n.
  21.  */
  22. class Solution {
  23.     public ListNode reverseBetween(ListNode head, int m, int n) {
  24.         if (m < 1) {
  25.             m = 1;
  26.         }
  27.         if (n < 1) {
  28.             n = 1;
  29.         }
  30.         if (head == null || head.next == null || m == n) {
  31.             return head;
  32.         }
  33.  
  34.         ListNode dummyHead = new ListNode(-1);
  35.         dummyHead.next = head;
  36.  
  37.         ListNode current = head;
  38.         ListNode previous = dummyHead;
  39.         int count = 1;
  40.         while (current != null && count < m) {
  41.             previous = current;
  42.             current = current.next;
  43.             count++;
  44.         }
  45.  
  46.         if (current == null || current.next == null) {
  47.             return head;
  48.         }
  49.  
  50.         ListNode nodeBeforeM = previous;
  51.         ListNode nodeAtM = current;
  52.  
  53.         previous = null;
  54.         while (current != null && count <= n) {
  55.             ListNode next = current.next;
  56.             current.next = previous;
  57.             previous = current;
  58.             current = next;
  59.             count++;
  60.         }
  61.  
  62.         nodeBeforeM.next = previous;
  63.         nodeAtM.next = current;
  64.  
  65.         return dummyHead.next;
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement