שאלה:
כתוב פעולה מקבלת רשימה לא ריקה ומחזירה המספר הגדול ברשימה.
פתרון בשפת java:
public static int max (Node<Integer> lst)
{
Node<Integer> p = lst;
int max = p.getValue();
//scan list
while(p!=null)
{
int x = p.getValue();
if(x>max)
max =x;
p=p.getNext();
}
return max;
}
יצירת רשימה שנראית כך:
n1 → 16 → 226 → 6 → null
Node<Integer> n3 = new Node<Integer>(6);
Node<Integer> n2 = new Node<Integer>(226,n3);
Node<Integer> n1 = new Node<Integer>(16,n2);
זימון הפונקציה:
System.out.println(max(n1));
פלט מתקבל:
226