From a711c88e9e76a89a7a3a80e3f97d243b15ceb7a6 Mon Sep 17 00:00:00 2001 From: Vedant Shrivastava Date: Tue, 5 Oct 2021 18:20:21 +0530 Subject: [PATCH] Create singlyLLrecursive.c --- Linked_list/singlyLLrecursive.c | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 Linked_list/singlyLLrecursive.c diff --git a/Linked_list/singlyLLrecursive.c b/Linked_list/singlyLLrecursive.c new file mode 100644 index 0000000..8b9612a --- /dev/null +++ b/Linked_list/singlyLLrecursive.c @@ -0,0 +1,2 @@ +public class SinglyLinkedList { private Node head; // Head is the first node in linked list public void append(T data){ if(head == null){ head = new Node(data); return; } tail().next = new Node(data); } private Node tail() { Node tail = head; // Find last element of linked list known as tail while(tail.next != null){ tail = tail.next; } return tail; } @Override public String toString(){ StringBuilder sb = new StringBuilder(); Node current = head; while(current != null){ sb.append(current).append("-->"); current = current.next; } if(sb.length() >=3){ sb.delete(sb.length() - 3, sb.length()); // to remove --> from last node } return sb.toString(); } /** * Reverse linked list using 3 pointers approach in O(n) time * It basically creates a new list by reversing direction, and * subsequently insert the element at the start of the list. */ public void reverseIteratively() { Node current = head; Node previous = null; Node forward = null; // traversing linked list until there is no more element while(current.next != null){ // Saving reference of next node, since we are changing current node forward = current.next; // Inserting node at start of new list current.next = previous; previous = current; // Advancing to next node current = forward; } head = current; head.next = previous; } /* * Reverse a singly linked list using recursion. In recursion Stack is * used to store data. * 1. Traverse linked list till we find the tail, * that would be new head for reversed linked list. */ private Node reverseRecursively(Node node){ Node newHead; //base case - tail of original linked list if((node.next == null)){ return node; } newHead = reverseRecursively(node.next); //reverse the link e.g. C->D->null will be null node.next.next = node; node.next = null; return newHead; } public void reverseRecursively(){ head = reverseRecursively(head); } private static class Node { private Node next; private T data; public Node(T data) { this.data = data; } @Override public String toString() { return data.toString(); } } } +