Question

Please show the java code and pseudocode as well Describe and implement a recursive algorithm for...

Please show the java code and pseudocode as well

Describe and implement a recursive algorithm for reversing a singly linked list L, so that the ordering of the nodes becomes opposite of what it was before. What is the running time of your algorithm on a list of n values? Provide both the growth function and BigOh complexity. Create a driver class to test your implementation.

Homework Answers

Answer #1

Algorithm reverse(current, previous):

Node temp

if(current=tail)

current.setNext(previous)

temp<head

L.setHead(tail)

L.setTail(temp)

else

reverse(current.getNext(), current)

current.setNext(previous)

Recursive Algorithm to fimd running time and space usage:

Algorithm Max (A, m, n)

if A[n-1]>m

m <= A[n-1]

if n=1

return m

else

return Max(A, m, n-1)

JAVA CODE:

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() &gt;=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();
        }
    }
 
}

Test Class

/** * Java program to test code of reversing singly linked list in Java.

* This test class test both iterative and recursive solution. Since

* the same list is first reversed using loops, and then again using recursion.

* You can see that final output is same as original linked list.

public class SinglyLinkedListTest {

public static void main(String args[]) {

SinglyLinkedList linkedlist = getDefaultList();

System.out.println("linked list before reversing : " + linkedlist); linkedlist.reverseIteratively();

System.out.println("linked list after reversing : " + linkedlist); linkedlist.reverseRecursively();

System.out.println("linked list after reversing recursively: " + linkedlist);

}

private static SinglyLinkedList getDefaultList(){

SinglyLinkedList linkedlist = new SinglyLinkedList();

linkedlist.append("A"); linkedlist.append("B"); linkedlist.append("C"); linkedlist.append("D"); linkedlist.append("E"); linkedlist.append("F");

return linkedlist;

}

}

Output:

linked list before reversing : A-->B-->C-->D-->E-->F linked list after reversing : F-->E-->D-->C-->B-->A linked list after reversing recursively: A-->B-->C-->D-->E-->F

Read more: https://javarevisited.blogspot.com/2017/03/how-to-reverse-linked-list-in-java-using-iteration-and-recursion.html#ixzz6am4uFqy5

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
PYTHON : Describe a fast recursive algorithm for reversing a singly linked list
PYTHON : Describe a fast recursive algorithm for reversing a singly linked list
Write an iterative algorithm in Java-like pseudocode for printing a singly linked list in reverse in...
Write an iterative algorithm in Java-like pseudocode for printing a singly linked list in reverse in O(N) time. You can use as much extra space as you need. The original list pointers CAN NOT BE MODIFIED. State in big-O notation how much extra space is used by this algorithm. Write another iterative algorithm in Java-like pseudocode for printing a singly linked list in reverse using O(1) extra space. The original list pointers CAN NOT BE MODIFIED. This algorithm can have...
Write a C++ recursive function that counts the number of nodes in a singly linked list....
Write a C++ recursive function that counts the number of nodes in a singly linked list. (a) Test your function using different singly linked lists. Include your code. (b) Write a recurrence relation that represents your algorithm. (c) Solve the recurrence relation using the iterating or recursive tree method to obtain the running time of the algorithm in Big-O notation.
Used the next seudoucode pseudocode and implement in the next code below run in c ++...
Used the next seudoucode pseudocode and implement in the next code below run in c ++ this code What is the output of the following pseudocode, where num1 , num2 , and num3 are integer variables? num1 = 5 num2 = 1 num3 = 4 aQueue.enqueue(num2) aQueue.enqueue(num3) aQueue.dequeue() aQueue.enqueue(num1 - num2) num1 = aQueue.peek() aQueue.dequeue() num2 = aQueue.peek() aQueue.dequeue() cout << num2 << " " << num1 << " " << num3 << endl ____________________________________________________________________________________ a// Created by Frank M....
The main goal is to implement two recursive methods, each is built to manipulate linked data...
The main goal is to implement two recursive methods, each is built to manipulate linked data structures. To host these methods you also have to define two utterly simplified node classes. 1.) Add a class named BinaryNode to the project. This class supports the linked representation of binary trees. However, for the BinaryNode class Generic implementation not needed, the nodes will store integer values The standard methods will not be needed in this exercise except the constructor 2.) Add a...
JAVA: Design and implement a recursive version of a binary search.  Instead of using a loop to...
JAVA: Design and implement a recursive version of a binary search.  Instead of using a loop to repeatedly check for the target value, use calls to a recursive method to check one value at a time.  If the value is not the target, refine the search space and call the method again.  The name to search for is entered by the user, as is the indexes that define the range of viable candidates can be entered by the user (that are passed to...
Write code in java Implement a method to build an AVL tree out of a sorted...
Write code in java Implement a method to build an AVL tree out of a sorted (ascending order) array of unique integers, with the fastest possible big O running time. You may implement private helper methods as necessary. If your code builds a tree that is other than an AVL tree, you will not get any credit. If your code builds an AVL tree, but is not the fastest big O implementation, you will get at most 12 points. You...
C++ please Write code to implement the Karatsuba multiplication algorithm in the file linked in Assignment...
C++ please Write code to implement the Karatsuba multiplication algorithm in the file linked in Assignment 2 (karatsuba.cpp) in Canvas (please do not rename file or use cout/cin statements in your solution). As a reminder, the algorithm uses recursion to produce the results, so make sure you implement it as a recursive function. Please develop your code in small The test program (karatsuba_test.cpp) is also given. PLEASE DO NOT MODIFY THE TEST FILE. KARATSUBA.CPP /* Karatsuba multiplication */ #include <iostream>...
Java Please [(1)] A palindrome is a string that reads the same forwards as backwards. Using...
Java Please [(1)] A palindrome is a string that reads the same forwards as backwards. Using only a fixed number of stacks and queues, the stack and queue ADT functions, and a fixed number of int and char variables, write an algorithm to determine if a string is a palindrome. Assume that the string is read from standard input one character at a time. The algorithm should output true or false as appropriate [(2)] Let Q be a non-empty queue,...
1. Given an n-element array A, Algorithm X executes an O(n)-time computation for each even number...
1. Given an n-element array A, Algorithm X executes an O(n)-time computation for each even number in A and an O(log n)-time computation for each odd number in A. What is the best-case running time of Algorithm X? What is the worst-case running time of Algorithm X? 2. Given an array, A, of n integers, give an O(n)-time algorithm that finds the longest subarray of A such that all the numbers in that subarray are in sorted order. Your algorithm...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT