19. Remove Nth Node From End of List #
Problem #
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Follow up: Could you do this in one pass?
Example 1:

Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2:
Input: head = [1], n = 1
Output: []
Example 3:
Input: head = [1,2], n = 1
Output: [1]
Constraints:
- The number of nodes in the list is
sz. 1 <= sz <= 300 <= Node.val <= 1001 <= n <= sz
Problem Summary #
Delete the nth node from the end of the linked list.
Solution Ideas #
This problem is relatively simple. First, loop once to get the total length of the linked list, then loop to the node before the node to be deleted and perform the deletion. One special case to note is that the head node may need to be deleted, which should be handled separately.
There is a particularly simple solution to this problem. Set up 2 pointers, with one pointer n positions ahead of the other. Move the 2 pointers at the same time, both moving the same distance. When one pointer reaches the end, the previous pointer is the nth node from the end.
Code #
package leetcode
import (
"github.com/halfrost/leetcode-go/structures"
)
// ListNode define
type ListNode = structures.ListNode
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
// Solution 1
func removeNthFromEnd(head *ListNode, n int) *ListNode {
dummyHead := &ListNode{Next: head}
preSlow, slow, fast := dummyHead, head, head
for fast != nil {
if n <= 0 {
preSlow = slow
slow = slow.Next
}
n--
fast = fast.Next
}
preSlow.Next = slow.Next
return dummyHead.Next
}
// Solution 2
func removeNthFromEnd1(head *ListNode, n int) *ListNode {
if head == nil {
return nil
}
if n <= 0 {
return head
}
current := head
len := 0
for current != nil {
len++
current = current.Next
}
if n > len {
return head
}
if n == len {
current := head
head = head.Next
current.Next = nil
return head
}
current = head
i := 0
for current != nil {
if i == len-n-1 {
deleteNode := current.Next
current.Next = current.Next.Next
deleteNode.Next = nil
break
}
i++
current = current.Next
}
return head
}