Question
I'm trying to learn recursion in Java by making a recursion method to print out an a reverse link list. PLease help me edit the
I'm trying to learn recursion in Java by making a recursion method to print out an a reverse link list. PLease help me edit the codes. Note: you cannot change the signature codes ( MylinkedList, ListNode, public reverse() ) , basically you can change stuff in the method private MyLinkedList reverse(ListNode Node){} Ex : good-->morning-->master-->!--> expecting: !-->master-->morning-->good-->
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | public class MyLinkedList { /** * The head of this list */ private ListNode head; /** * The number of data objects in this list currently. */ private int size; private Object MyLinkedList(); /** * inner class for ListNode */ private class ListNode { private Object data; private ListNode next; private ListNode(Object d) { this.data = d; this.next = null; } private ListNode() { } } /** * Constructor of linked list, creating an empty linked list with a dummy head * node. */ public MyLinkedList() { this.head = new ListNode(null); // an empty list with a dummy head node this.size = 0; } public MyLinkedList reverse() { // Please implement this recursive helper method below. // You have to use recursion. return reverse(this.head.next); } /** * TODO: THIS METHOD HAS TO USE RECURSION.YOU CANNOT CHANGE ITS SIGNATURE. * Helper method of public reverse() method. * * @param node * @return A new reversed MyLinkedList object. */ // This linkedList has dummy node private MyLinkedList reverse(ListNode node) { MyLinkedList ReverseList = new MyLinkedList(); //ListNode cur = node; if (node == null) return ReverseList;
else ReverseList.addLast(node.data); reverse(node.next);
return ReverseList;
} public void addFirst(Object data) { ListNode temp = new ListNode(data); temp.next = this.head.next; this.head.next = temp; this.size++; }
public void addLast (Object data){ if(this.head.next == null) addFirst(data); else { ListNode cur = this.head; while(cur.next != null){ cur = cur.next; } cur.next = new ListNode(data); this.size++; } }
public String toString() { String result = "( "; for (ListNode node = this.head.next; node != null; node = node.next) { result += node.data + "-->"; } return result + ")"; } } |
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