Advertisement
exmkg

Untitled

Sep 23rd, 2024
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.23 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * public class ListNode {
  4.  *     int val;
  5.  *     ListNode next;
  6.  *     ListNode() {}
  7.  *     ListNode(int val) { this.val = val; }
  8.  *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  9.  * }
  10.  */
  11. class Solution {
  12.     public ListNode removeNthFromEnd(ListNode head, int n) {
  13.         // Assume that linked list is as below
  14.         // (0) -> (1) -> (2) -> (3) -> (4) -> (5) -> (6) -> null
  15.         // and n = 3.
  16.         //
  17.         // Now, create two pointers `slow` and `fast` and
  18.         // initialize both to be at the head node.
  19.         // slow, fast (0) -> (1) -> (2) -> (3) -> (4) -> (5) -> (6) -> null
  20.         //
  21.         // Then, move `fast` pointer n = 3 nodes further to
  22.         // slow (0) -> (1) -> (2) -> fast (3) -> (4) -> (5) -> (6) -> null
  23.         // and then start walking both `slow` and `fast` one step at a time
  24.         // until fast.next is null.
  25.         //
  26.         // slow (0) -> (1) -> (2) -> fast (3) -> (4) -> (5) -> (6) -> null
  27.         // (0) -> slow (1) -> (2) -> (3) -> fast (4) -> (5) -> (6) -> null
  28.         // (0) -> (1) -> slow (2) -> (3) -> (4) -> fast (5) -> (6) -> null
  29.         // (0) -> (1) -> (2) -> slow (3) -> (4) -> (5) -> fast (6) -> null
  30.         //
  31.         // As you can see, `slow` pointer stopped one element before the one
  32.         // which should be removed (`slow.next` should be removed).
  33.         // Now, we remove `slow.next` by doing `slow.next = slow.next.next`,
  34.         // practically removing `slow.next` from the list.
  35.  
  36.         ListNode fast = head, slow = head;
  37.         for (int i = 0; i < n; i++) {
  38.             fast = fast.next;
  39.         }
  40.  
  41.         // The only corner case is that if n == length of the linked list, then
  42.         // we need to remove the head node. `fast` will be initially moved to the null
  43.         // after the tail element. If that's the case, practically remove the `head` node
  44.         // by returning the rest of the linked list (head.next) after `head`.
  45.         if (fast == null) {
  46.             return head.next;
  47.         }
  48.  
  49.         while (fast.next != null) {
  50.             fast = fast.next;
  51.             slow = slow.next;
  52.         }
  53.         slow.next = slow.next.next;
  54.         return head;
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement