You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
594 B

package deletemiddle
type ListNode struct {
Val int
Next *ListNode
}
func length(node *ListNode) int {
length := 0
for node != nil {
length++
node = node.Next
}
return length
}
func nth(node *ListNode, n int) *ListNode {
for i := 0; i < n; i++ {
node = node.Next
}
return node
}
func deleteMiddle(head *ListNode) *ListNode {
length := length(head)
if length <= 1 {
return nil
}
midIndex := length / 2
preceeding := nth(head, midIndex-1)
preceeding.Next = preceeding.Next.Next
return head
}
func Delete(head *ListNode) *ListNode {
return deleteMiddle(head)
}