1
+ package com .thealgorithms .datastructures .lists ;
2
+
3
+ import org .junit .jupiter .api .Test ;
4
+
5
+ import java .util .ArrayList ;
6
+ import java .util .List ;
7
+
8
+ import static org .junit .jupiter .api .Assertions .*;
9
+
10
+ public class SinglyLinkedListTest {
11
+
12
+ /**
13
+ * Initialize a list with natural order values with pre-defined length
14
+ * @param length
15
+ * @return linked list with pre-defined number of nodes
16
+ */
17
+ private SinglyLinkedList createSampleList (int length ) {
18
+ List <Node > nodeList = new ArrayList <>();
19
+ for (int i = 1 ; i <= length ; i ++) {
20
+ Node node = new Node (i );
21
+ nodeList .add (node );
22
+ }
23
+
24
+ for (int i = 0 ; i < length - 1 ; i ++) {
25
+ nodeList .get (i ).next = nodeList .get (i +1 );
26
+ }
27
+
28
+ return new SinglyLinkedList (nodeList .get (0 ), length );
29
+ }
30
+
31
+ @ Test
32
+ void detectLoop () {
33
+ //List has cycle
34
+ Node firstNode = new Node (1 );
35
+ Node secondNode = new Node (2 );
36
+ Node thirdNode = new Node (3 );
37
+ Node fourthNode = new Node (4 );
38
+
39
+ firstNode .next = secondNode ;
40
+ secondNode .next = thirdNode ;
41
+ thirdNode .next = fourthNode ;
42
+ fourthNode .next = firstNode ;
43
+
44
+ SinglyLinkedList listHasLoop = new SinglyLinkedList (firstNode , 4 );
45
+ assertTrue (listHasLoop .detectLoop ());
46
+
47
+ SinglyLinkedList listHasNoLoop = createSampleList (5 );
48
+ assertFalse (listHasNoLoop .detectLoop ());
49
+ }
50
+
51
+ @ Test
52
+ void middle () {
53
+ int oddNumberOfNode = 7 ;
54
+ SinglyLinkedList list = createSampleList (oddNumberOfNode );
55
+ assertEquals (oddNumberOfNode /2 + 1 , list .middle ().value );
56
+ int evenNumberOfNode = 8 ;
57
+ list = createSampleList (evenNumberOfNode );
58
+ assertEquals (evenNumberOfNode /2 , list .middle ().value );
59
+ }
60
+
61
+ @ Test
62
+ void swap () {
63
+ SinglyLinkedList list = createSampleList (5 );
64
+ assertEquals (1 , list .getHead ().value );
65
+ assertEquals (5 , list .getNth (4 ));
66
+ list .swapNodes (1 ,5 );
67
+ assertEquals (5 , list .getHead ().value );
68
+ assertEquals (1 , list .getNth (4 ));
69
+ }
70
+
71
+ @ Test
72
+ void clear () {
73
+ SinglyLinkedList list = createSampleList (5 );
74
+ assertEquals (5 , list .size ());
75
+ list .clear ();
76
+ assertEquals (0 , list .size ());
77
+ assertTrue (list .isEmpty ());
78
+ }
79
+
80
+ @ Test
81
+ void search () {
82
+ SinglyLinkedList list = createSampleList (10 );
83
+ assertTrue (list .search (5 ));
84
+ assertFalse (list .search (20 ));
85
+ }
86
+
87
+ @ Test
88
+ void deleteNth () {
89
+ SinglyLinkedList list = createSampleList (10 );
90
+ assertTrue (list .search (7 ));
91
+ list .deleteNth (6 ); //Index 6 has value 7
92
+ assertFalse (list .search (7 ));
93
+ }
94
+ }
0 commit comments