In: Computer Science
write the method “getMaxValue” that finds and returns the maximum value in an integer linked list. If the list is empty, then it should return 0.
use the provided code below
public class Question03 { public class ListNode//public for testing purposes { public int data;//public for testing purposes public ListNode link;//public for testing purposes public ListNode(int aData, ListNode aLink) { data = aData; link = aLink; } } public ListNode head;//public for testing purposes public int getMaxValue() { //----------------------------------------------------------------------------------- //Write your solution here }//Do not alter this //Write additional methods or properties here //-------------------------------------------------------------------------------- //Test your code here. You may alter this as needed. public static void main(String[] args) { //Example Question03 intLL = new Question03(); intLL.head = intLL.new ListNode(0, intLL.new ListNode(1, intLL.new ListNode(2, intLL.new ListNode(3, intLL.new ListNode(4,null))))); int max = intLL.getMaxValue(); System.out.println(max); } //-------------------------------------------------------------------------------- }//Do not alter this
public ListNode head;//public for testing purposes,public ListNode head=null;
public int getMaxValue()
{
ListNode temp=head; //head assigned to temp,not to alter the haead
int max;
if(head==null) //if no elements, return 0
{//System.out.println("no elements");
return 0;
}
else
{
max=head.data; //head data is assigned to max
while(temp!=null) // traverse the list
{
// System.out.println(temp.data);
if(max<temp.data) //if temp.data > max, the assign it as max
{
max=temp.data;
}
temp=temp.link; //temp points to next node
}
}
return max;
}//Do not alter this