Skip to content

Commit ae6c03a

Browse files
authored
Merge pull request #13 from fabiothiroki/linkedlist
add linked list problem
2 parents e4c25cf + 4afe82d commit ae6c03a

File tree

2 files changed

+92
-0
lines changed

2 files changed

+92
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package removeduplicates
2+
3+
import "fmt"
4+
5+
// Node is a linked list representation
6+
type Node struct {
7+
value int
8+
next *Node
9+
}
10+
11+
// CountElements returns a map with each element occurrence
12+
func CountElements(head *Node) map[int]int {
13+
m := make(map[int]int)
14+
15+
l := head
16+
for l != nil {
17+
m[head.value]++
18+
19+
l = l.next
20+
}
21+
22+
return m
23+
}
24+
25+
func RemoveElement(head *Node, element int) *Node {
26+
if head.value == element {
27+
return head.next
28+
}
29+
30+
l := head
31+
for l != nil {
32+
33+
if l.next != nil && l.next.value == element {
34+
l.next = l.next.next
35+
} else {
36+
l = l.next
37+
}
38+
}
39+
return head
40+
}
41+
42+
// RemoveDuplicates returns a linked list without duplicated values
43+
func RemoveDuplicates(head *Node) *Node {
44+
if head == nil {
45+
return head
46+
}
47+
48+
m := CountElements(head)
49+
50+
l2 := head
51+
for l2 != nil {
52+
if m[l2.value] > 1 {
53+
head = RemoveElement(head, l2.value)
54+
m[l2.value]--
55+
}
56+
57+
l2 = l2.next
58+
}
59+
60+
fmt.Println(head)
61+
62+
return head
63+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package removeduplicates
2+
3+
import "testing"
4+
5+
func TestNilList(t *testing.T) {
6+
r := RemoveDuplicates(nil)
7+
if r != nil {
8+
t.Errorf("Got: %p, want: nil.", r)
9+
}
10+
}
11+
12+
func TestDuplicatesList(t *testing.T) {
13+
n2 := &Node{
14+
value: 2,
15+
next: nil,
16+
}
17+
18+
n1 := &Node{
19+
value: 2,
20+
next: n2,
21+
}
22+
23+
r := RemoveDuplicates(n1)
24+
25+
m := CountElements(r)
26+
if m[2] != 1 {
27+
t.Errorf("Got: %d, want: 1.", m[2])
28+
}
29+
}

0 commit comments

Comments
 (0)