给定一个单链表的头节点head,每个节点都有value(>0),给定一个正数m,
value%m的值一样的节点算一类,
请把所有的类根据单链表的方式重新连接好,返回每一类的头节点。
自然智慧即可。用map。
代码用golang编写。代码如下:
package main
import "fmt"
func main() {
head := &Node{value: 10}
head.next = &Node{value: 11}
head.next.next = &Node{value: 7}
head.next.next.next = &Node{value: 4}
head.next.next.next.next = &Node{value: 5}
head.next.next.next.next.next = &Node{value: 13}
head.next.next.next.next.next.next = &Node{value: 14}
ret := split(head, 3)
for i := 0; i < len(ret); i++ {
nod := ret[i]
for nod != nil {
fmt.Print(nod, " ")
nod = nod.next
}
fmt.Println("")
}
}
type Node struct {
value int
next *Node
}
type Ht struct {
h *Node
t *Node
}
func NewHt(a *Node) *Ht {
ret := &Ht{}
ret.h = a
ret.t = a
return ret
}
func split(h *Node, m int) []*Node {
map0 := make(map[int]*Ht)
for h != nil {
next := h.next
h.next = nil
mod := h.value % m
if _, ok := map0[mod]; !ok {
map0[mod] = NewHt(h)
} else {
map0[mod].t.next = h
map0[mod].t = h
}
h = next
}
ans := make([]*Node, m)
for mod, _ := range map0 {
ans[mod] = map0[mod].h
}
return ans
}
执行结果如下: