Share My 3ms Golang Solution.


  • 0
    H
    func removeNthFromEnd(head *ListNode, n int) *ListNode {
    	fastNode := head
    	slowNode := &ListNode{Val: head.Val, Next: head}
    	var flag bool
    
    	for n > 1 {
    		fastNode = fastNode.Next
    		n--
    	}
    	for fastNode.Next != nil {
    		fastNode = fastNode.Next
    		slowNode = slowNode.Next
    		flag = true
    	}
    
    	slowNode.Next = slowNode.Next.Next
    	if flag {
    		return head
    	}
    	return head.Next
    }
    

    The var flag bool solve remove the lastest element.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.