Home [Algorithm] Remove Nth Node From End of List
Post
Cancel

[Algorithm] Remove Nth Node From End of List

‘Remove Nth Node From End of List’ in LeetCode (Medium)


📌 Problem

https://leetcode.com/problems/remove-nth-node-from-end-of-list/

📌 Answer

Two-Pointer

The point

  • For a singly linked list, used two pointer ‘fast’, ‘slow’

The time and space complexity is quite good.

Screen Shot 2021-10-26 at 7 05 36 PM

Result

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        
        ListNode start = new ListNode(0);

        // two pointer
        ListNode slow = start, fast = start;
        start.next = head;
        
        
        for (int i = 1; i <= n + 1; i++) {
            fast = fast.next;
        }
        
        while (fast != null) {
            slow = slow.next;
            fast = fast.next;
        }

        slow.next = slow.next.next;

        return start.next;
    }
}
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
/**
[Question]
- remove the nth node from the end of the list
- return its head.

[Condition]
- The number of nodes in the list is sz. 
**/

The source : https://leetcode.com/problems/remove-nth-node-from-end-of-list/discuss/589304/CLEAR-JAVA-SOLUTION-WITH-DETAILED-EXPLANATION! And ⭐️ it’s the best explanation


I’m not good at singly linked list….
Let’s search it.

This post is licensed under CC BY 4.0 by the author.

[Algorithm] Letter Combinations of a Phone Number

[Algorithm] Generate Parentheses

Comments powered by Disqus.