Add Recursive Reverse of Linked List (#4292)

Co-authored-by: BamaCharanChhandogi <b.c.chhandogi@gmailcom>
This commit is contained in:
Bama Charan Chhandogi
2023-08-10 14:08:56 +05:30
committed by GitHub
parent 1ef5208b75
commit 4fe419ebd8
2 changed files with 69 additions and 5 deletions

View File

@ -119,10 +119,10 @@ public class SinglyLinkedList extends Node {
}
/**
* Reverse a singly linked list from a given node till the end
* Reverse a singly linked list[Iterative] from a given node till the end
*
*/
public Node reverseList(Node node) {
public Node reverseListIter(Node node) {
Node prev = null;
Node curr = node;
@ -141,6 +141,23 @@ public class SinglyLinkedList extends Node {
// the reversed linkedlist
return prev;
}
/**
* Reverse a singly linked list[Recursive] from a given node till the end
*
*/
public Node reverseListRec(Node head) {
if (head == null || head.next == null) {
return head;
}
Node prev = null;
Node h2 = reverseListRec(head.next);
head.next.next = head;
head.next = prev;
return h2;
}
/**
* Clear all nodes in the list