parent
b3b965ba0a
commit
9790a5d6c5
@ -0,0 +1,42 @@
|
||||
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)
|
||||
|
||||
}
|
@ -0,0 +1,46 @@
|
||||
package deletemiddle_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
dm "git.jxs.me/leetgo/deletemiddle"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func buildList(values []int) *dm.ListNode {
|
||||
var result *dm.ListNode
|
||||
|
||||
for i := len(values) - 1; i >= 0; i-- {
|
||||
result = &dm.ListNode{Val: values[i], Next: result}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func TestEmpty(t *testing.T) {
|
||||
var head *dm.ListNode
|
||||
require.Nil(t, dm.Delete(head))
|
||||
}
|
||||
|
||||
func TestOne(t *testing.T) {
|
||||
head := buildList([]int{1})
|
||||
require.Nil(t, dm.Delete(head))
|
||||
}
|
||||
|
||||
func TestTwo(t *testing.T) {
|
||||
head := buildList([]int{2, 1})
|
||||
expected := buildList([]int{2})
|
||||
require.Equal(t, expected, dm.Delete(head))
|
||||
}
|
||||
|
||||
func TestFour(t *testing.T) {
|
||||
head := buildList([]int{1, 2, 3, 4})
|
||||
expected := buildList([]int{1, 2, 4})
|
||||
require.Equal(t, expected, dm.Delete(head))
|
||||
}
|
||||
|
||||
func TestExample1(t *testing.T) {
|
||||
head := buildList([]int{1, 3, 4, 7, 1, 2, 6})
|
||||
expected := buildList([]int{1, 3, 4, 1, 2, 6})
|
||||
require.Equal(t, expected, dm.Delete(head))
|
||||
}
|
Loading…
Reference in new issue