SHARE
TWEET

19. Remove Nth Node From End of List|Time: O(n)|Space: O(1)

a guest Aug 26th, 2019 78 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Problem: https://leetcode.com/problems/remove-nth-node-from-end-of-list
  2. // Solution: https://leetcode.com/problems/remove-nth-node-from-end-of-list/solution/
  3.  
  4. /**
  5.  * Definition for singly-linked list.
  6.  * public class ListNode {
  7.  *     int val;
  8.  *     ListNode next;
  9.  *     ListNode(int x) { val = x; }
  10.  * }
  11.  */
  12. class Solution {
  13.     public ListNode removeNthFromEnd(ListNode head, int n) {
  14.         ListNode dummy = new ListNode(0);
  15.         dummy.next = head;
  16.         ListNode first = dummy;
  17.         ListNode second = dummy;
  18.  
  19.         // Advances first pointer so that the gap between first and second is n nodes apart
  20.         for (int i = 1; i <= n + 1; i++) {
  21.             first = first.next;
  22.         }
  23.        
  24.         // Move first to the end, maintaining the gap
  25.         while (first != null) {
  26.             first = first.next;
  27.             second = second.next;
  28.         }
  29.        
  30.         second.next = second.next.next;
  31.         return dummy.next;
  32.     }
  33. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top