Fix NullPointer Exception (#4142)

This commit is contained in:
Akshith121
2023-04-15 13:40:39 +05:30
committed by GitHub
parent 0c618b5ee8
commit 1ce907625b
2 changed files with 74 additions and 10 deletions

View File

@ -122,20 +122,23 @@ public class SinglyLinkedList extends Node {
* Reverse a singly linked list from a given node till the end
*
*/
Node reverseList(Node node) {
Node prevNode = head;
while (prevNode.next != node) {
prevNode = prevNode.next;
}
Node prev = null, curr = node, next;
while (curr != null) {
next = curr.next;
public Node reverseList(Node node) {
Node prev = null;
Node curr = node;
while (curr != null && curr.next != null) {
Node next=curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
prevNode.next = prev;
return head;
//when curr.next==null, the current element is left without pointing it to its prev,so
if(curr != null){
curr.next = prev;
prev=curr;
}
//prev will be pointing to the last element in the Linkedlist, it will be the new head of the reversed linkedlist
return prev;
}
/**