mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-09 03:59:38 +08:00
Add Recursive Reverse of Linked List (#4292)
Co-authored-by: BamaCharanChhandogi <b.c.chhandogi@gmailcom>
This commit is contained in:

committed by
GitHub

parent
1ef5208b75
commit
4fe419ebd8
@ -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
|
||||
|
Reference in New Issue
Block a user