Question
Java Given the array, which has been converted to a linked list, I need to invoke a remove method to remove a number from the
Java
Given the array, which has been converted to a linked list, I need to invoke a remove method to remove a number from the list. The output for the first array should come out like this Now list1 = 24->18->3-7->null Now list2 = 31->-9->5->21->4->0->8->null Now lsit3 = 5->0->1->null
but i keep getting this output Now list1= 12->3->7->null Now list2= -7->null Now list3= 5->0->1->null
int arr1[] = {24, 18, 12, 3, 7}; int arr2[] = {31, -9, 5, 21, 4, 0, 8, -7}; int arr3[] = {5, 5, 0, 1};
IntNode list1, list2, list3, list4, list5, list6; list1 = createList(arr1); list2 = createList(arr2); list3 = createList(arr3);
System.out.println("to begin with, "); System.out.println("list1= " + toString(list1)); System.out.println("list2= " + toString(list2)); System.out.println("list3= " + toString(list3));
list1 = remove(list1,12); // remove returns the new list so that list1 changes list2 = remove(list2, -7); // invoke your method to remove -7 from list2 list3 = remove(list3, 5); // invoke your method to remove 5 from list3
System.out.println("Now list1= " + toString(list1)); System.out.println("Now list2= " + toString(list2)); System.out.println("Now list3= " + toString(list3));
So far my remove method looks like this:
public static IntNode remove(IntNode head,int value){ IntNode current = head; IntNode prev = null; if( current != null && current.data == value){ return head = current.next; } while( current != null && current.data != value){ //prev = current; current = current.next; } prev = current; return current; }
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