Question
this is QUESTION : 1 Write a method that return SinglyLinkedList as reversed string For example: If the elements of a list is 1, 2,
this is QUESTION :
1 Write a method that return SinglyLinkedList as reversed string
For example:
If the elements of a list is
1, 2, 3, 4, 5, 6
the reverse string should be
6, 5, 4, 3, 2, 1
it should be printed in main
hint: a new list maybe a solution. use addFirst() or addLast()
implement reverse method
you have two steps:
1- creating a new linked list and all node of the first linked list to the new linked list in reverse order (you should use one of the two method addFirst() or addLast() to add in reverse
2- you should traverse the new list and add the element inside each node to string don't forget the space in the string. and there is no comma after last element
class Main { public static void main(String[] args) { //test your implmentation here SinglyLinkedList
class SinglyLinkedList
private Node
public void addFirst(E e) { // adds element e to the front of the list head = new Node<>(e, head); // create and link a new node if (size == 0) tail = head; // special case: new node becomes tail also size++; } public void addLast(E e) { // adds element e to the end of the list Node
public E first() { // returns (but does not remove) the first element if (isEmpty()) return null; return head.getElement(); } public E last( ) { // returns (but does not remove) the last element if (isEmpty( )) return null; return tail.getElement( ); } //implment this Method public String reverse() { String s=""; SinglyLinkedList l2= new SinglyLinkedList(); Node c =head; //define a new list and add the element of the current list to it in revrse order //you should use one of the two method addFirst() or addLast() to add in reverse } //note that there are no comma after last elment. //loop the new linked list to store the element on s } return s; } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started