Skip to content

Commit 7b431d7

Browse files
committed
fixed double linked list and create test for it
1 parent 0a282fa commit 7b431d7

File tree

2 files changed

+94
-0
lines changed

2 files changed

+94
-0
lines changed

datastructures/linkedlist/doublylinkedlist/doublylinkedlist.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,13 @@ func NewNode(val int) *Node {
2828
func (ll *DoubleLinkedList) AddAtBeg(val int) {
2929
n := NewNode(val)
3030
n.next = ll.head
31+
32+
if ll.head != nil{
33+
ll.head.prev = n
34+
}
35+
3136
ll.head = n
37+
3238
}
3339

3440
// AddAtEnd Add a node at the end of the linkedlist
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
package doublylinkedlist
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
func TestDoubleLinkedList(t *testing.T) {
9+
newList := DoubleLinkedList{}
10+
11+
newList.AddAtBeg(1)
12+
newList.AddAtBeg(2)
13+
newList.AddAtBeg(3)
14+
15+
t.Run("Test AddAtBeg", func(t *testing.T) {
16+
wantNext := []int{3, 2, 1}
17+
wantPrev := []int{1, 2, 3}
18+
got := []int{}
19+
20+
// check from next address
21+
current := newList.head
22+
23+
got = append(got, current.val)
24+
25+
for current.next != nil {
26+
current = current.next
27+
got = append(got, current.val)
28+
}
29+
30+
if !reflect.DeepEqual(got, wantNext) {
31+
t.Errorf("got: %v, want: %v", got, wantNext)
32+
}
33+
34+
// check from prev address
35+
got = []int{}
36+
got = append(got, current.val)
37+
38+
for current.prev != nil {
39+
current = current.prev
40+
got = append(got, current.val)
41+
}
42+
43+
if !reflect.DeepEqual(got, wantPrev) {
44+
t.Errorf("got: %v, want: %v", got, wantPrev)
45+
}
46+
})
47+
48+
newList.AddAtEnd(4)
49+
50+
t.Run("Test AddAtEnd", func(t *testing.T) {
51+
want := []int{3, 2, 1, 4}
52+
got := []int{}
53+
current := newList.head
54+
got = append(got, current.val)
55+
for current.next != nil {
56+
current = current.next
57+
got = append(got, current.val)
58+
}
59+
if !reflect.DeepEqual(got, want) {
60+
t.Errorf("got: %v, want: %v", got, want)
61+
}
62+
})
63+
64+
t.Run("Test DelAtBeg", func(t *testing.T) {
65+
want := 3
66+
got := newList.DelAtBeg()
67+
if got != want {
68+
t.Errorf("got: %v, want: %v", got, want)
69+
}
70+
})
71+
72+
t.Run("Test DelAtEnd", func(t *testing.T) {
73+
want := 4
74+
got := newList.DelAtEnd()
75+
if got != want {
76+
t.Errorf("got: %v, want: %v", got, want)
77+
}
78+
})
79+
80+
t.Run("Test Count", func(t *testing.T) {
81+
want := 2
82+
got := newList.Count()
83+
if got != want {
84+
t.Errorf("got: %v, want: %v", got, want)
85+
}
86+
})
87+
88+
}

0 commit comments

Comments
 (0)