mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-06 17:29:31 +08:00
Fix NullPointer Exception (#4142)
This commit is contained in:
@ -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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
Reference in New Issue
Block a user