019-删除链表的倒数第N个节点

Description

给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

说明: 给定的 n 保证是有效的。 进阶: 你能尝试使用一趟扫描实现吗?

Example
给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.
Solution
type ListNode struct {
    Val int
    Next *ListNode
}

func formatList2Node(list []int)*ListNode  {
    head := new(ListNode)
    current := head
    for i := range list{
        current.Next = new(ListNode)
        current.Next.Val = list[i]
        current = current.Next
    }
    return head.Next
}


func removeNthFromEnd(head *ListNode, n int) *ListNode {
    dummy := new(ListNode)
    dummy.Next = head
    left := dummy
    right := dummy
    for i := 0 ;i < n; i ++ {
        if right.Next == nil {
            return nil
        }
        right = right.Next
    }
    for right.Next != nil {
        right = right.Next
        left = left.Next
    }
    left.Next = left.Next.Next
    return dummy.Next
}


//testing
func TestRemoveNNode(t *testing.T)  {
    list := []int{1,2,3,4,5}
    node := formatList2Node(list)
    newNode  := removeNthFromEnd(node,2)
    for newNode != nil {
        fmt.Println(newNode.Val)
        newNode = newNode.Next
    }

}

leetCode地址