-
Notifications
You must be signed in to change notification settings - Fork 0
/
remove-duplicates-from-sorted-list-ii.go
65 lines (60 loc) · 1.16 KB
/
remove-duplicates-from-sorted-list-ii.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
// `golint` keeps adding imports used in other .go files
// Please ignore if they are not actually used here
"fmt"
"strconv"
"strings"
)
// ListNode is the node type for linked list
type ListNode struct {
Val int
Next *ListNode
}
func deleteDuplicates(head *ListNode) (ret *ListNode) {
ret = head
var prevP *ListNode
for head != nil && head.Next != nil {
if head.Val == head.Next.Val {
nextP := head.Next.Next
for nextP != nil {
if nextP.Val != head.Val {
break
}
nextP = nextP.Next
}
if prevP == nil {
head = nextP
ret = nextP
} else {
prevP.Next = nextP
head = prevP.Next
}
} else {
prevP = head
head = head.Next
}
}
return
}
func main() {
test := &ListNode{1, &ListNode{1, &ListNode{2, nil}}}
test.Print()
result := deleteDuplicates(test)
result.Print()
}
// Print is a util func to print linked lists
func (list *ListNode) Print() {
if list == nil {
fmt.Println()
return
}
var str strings.Builder
str.WriteString(strconv.Itoa(list.Val))
list = list.Next
for list != nil {
str.WriteString(" " + strconv.Itoa(list.Val))
list = list.Next
}
fmt.Println(str.String())
}