2 回答

TA貢獻1853條經驗 獲得超9個贊
通過單獨解決每個案例,您的解決方案過于復雜。如果要進行重復數據刪除:
current:=head
for current.Next!=nil {
if current.Next.Val==current.Val {
// Remove the duplicate node, stay on the same node
curent.Next=current.Next.Next
} else {
// Advance to the next node
current=current.Next
}
}
如果要刪除重復值的所有實例:
current:=head
var prev *ListNode
for current!=nil {
trc:=current
// Find the next node with a different value
for trc!=nil {
if trc.Val==current.Val {
trc=trc.Next
} else {
break
}
}
// if trc==nil, all remaining values are the same
// if prev is also nil, all values in the list are the same
if trc==nil {
if prev==nil {
// All values in the list are the same
} else {
prev.Next=nil
current=nil
}
} else if trc==current {
// Not a duplicate entry
prev=current
current=current.Next
} else {
if prev!=nil {
prev.Next=trc.Next
} else {
// you need to set head = trc.Next
}
current=trc.Next
}
}

TA貢獻1797條經驗 獲得超4個贊
乍一看,它看起來微不足道,但在深入研究之后,問題實際上真的很煩人。您必須考慮三種情況。元素可以在前面重復。除非你找到單個元素,否則你必須搜索頭部。其他兩種情況可以通過一種算法解決,因為節點的nil旁邊設置并不重要。
package main
import "fmt"
type LL struct {
Val int
Next *LL
}
func removeDuplicates(h *LL) (res *LL) {
current := h
var prev *LL
// annoying
if current.Next == nil {
return current
}
// even more annoying
if current.Next.Val != current.Val {
res = current
}
for current.Next != nil {
if current.Next.Val == current.Val {
current.Next = current.Next.Next
// trailing case - most annoying of them all
if prev != nil && (current.Next == nil || current.Next.Val != current.Val) {
prev.Next = current.Next
}
} else {
prev = current
current = current.Next
// front repetition - decently annoying
if res == nil && (current.Next == nil || current.Next.Val != current.Val) {
res = current
}
}
}
return
}
func main() {
l := &LL{1, &LL{1, &LL{2, &LL{2, &LL{3, &LL{4, &LL{4, &LL{5, &LL{6, &LL{6, nil}}}}}}}}}}
l = removeDuplicates(l)
current := l
for current != nil {
fmt.Print(current.Val)
current = current.Next
}
fmt.Println(l)
}
- 2 回答
- 0 關注
- 101 瀏覽
添加回答
舉報