Advertisement
1988coder

19. Remove Nth Node From End of List

Jan 6th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.07 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
  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.  * Two pointer.
  15.  *
  16.  * Time Complexity: O(N)
  17.  *
  18.  * Space Complexity: O(1)
  19.  *
  20.  * N = Length of input list.
  21.  */
  22. class Solution {
  23.     public ListNode removeNthFromEnd(ListNode head, int n) {
  24.         if (head == null) {
  25.             return null;
  26.         }
  27.  
  28.         ListNode dummyNode = new ListNode(-1);
  29.         dummyNode.next = head;
  30.         ListNode fast = dummyNode;
  31.         ListNode slow = dummyNode;
  32.  
  33.         while (n > 0) {
  34.             if (fast.next == null) {
  35.                 return head;
  36.             }
  37.             fast = fast.next;
  38.             n--;
  39.         }
  40.  
  41.         while (fast.next != null) {
  42.             fast = fast.next;
  43.             slow = slow.next;
  44.         }
  45.  
  46.         ListNode toBeRemoved = slow.next;
  47.         slow.next = toBeRemoved.next;
  48.         toBeRemoved.next = null;
  49.  
  50.         return dummyNode.next;
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement