1
1
package com .thealgorithms .datastructures .lists ;
2
2
3
+
3
4
import org .junit .jupiter .api .Test ;
4
5
5
6
import java .util .ArrayList ;
@@ -99,4 +100,64 @@ void deleteNth() {
99
100
list .deleteNth (6 ); //Index 6 has value 7
100
101
assertFalse (list .search (7 ));
101
102
}
103
+ //Test to check whether the method reverseList() works fine
104
+ @ Test
105
+ void reverseList (){
106
+
107
+ //Creating a new LinkedList of size:4
108
+ //The linkedlist will be 1->2->3->4->null
109
+ SinglyLinkedList list = createSampleList (4 );
110
+
111
+ //Reversing the LinkedList using reverseList() method and storing the head of the reversed linkedlist in a head node
112
+ //The reversed linkedlist will be 4->3->2->1->null
113
+ Node head =list .reverseList (list .getHead ());
114
+
115
+ //Recording the Nodes after reversing the LinkedList
116
+ Node firstNode = head ; //4
117
+ Node secondNode = firstNode .next ; //3
118
+ Node thirdNode = secondNode .next ; //2
119
+ Node fourthNode = thirdNode .next ; //1
120
+
121
+ //Checking whether the LinkedList is reversed or not by comparing the original list and reversed list nodes
122
+ assertEquals (1 ,fourthNode .value );
123
+ assertEquals (2 ,thirdNode .value );
124
+ assertEquals (3 ,secondNode .value );
125
+ assertEquals (4 ,firstNode .value );
126
+ }
127
+
128
+ //Test to check whether implemented reverseList() method handles NullPointer Exception for TestCase where head==null
129
+ @ Test
130
+ void reverseListNullPointer (){
131
+ //Creating a linkedlist with first node assigned to null
132
+ SinglyLinkedList list =new SinglyLinkedList ();
133
+ Node first =list .getHead ();
134
+
135
+ //Reversing the linkedlist
136
+ Node head =list .reverseList (first );
137
+
138
+ //checking whether the method works fine if the input is null
139
+ assertEquals (head ,first );
140
+ }
141
+
142
+ //Testing reverseList() method for a linkedlist of size: 20
143
+ @ Test
144
+ void reverseListTest (){
145
+ //Creating a new linkedlist
146
+ SinglyLinkedList list = createSampleList (20 );
147
+
148
+ //Reversing the LinkedList using reverseList() method and storing the head of the reversed linkedlist in a head node
149
+ Node head =list .reverseList (list .getHead ());
150
+
151
+ //Storing the head in a temp variable, so that we cannot loose the track of head
152
+ Node temp =head ;
153
+
154
+ int i =20 ; //This is for the comparison of values of nodes of the reversed linkedlist
155
+ //Checking whether the reverseList() method performed its task
156
+ while (temp !=null && i >0 ){
157
+ assertEquals (i ,temp .value );
158
+ temp =temp .next ;
159
+ i --;
160
+ }
161
+ }
162
+
102
163
}
0 commit comments