Я пытаюсь решить задачу максимального элемента из hackerrank. Задача link Идея заключается в реализации Stack through linked list с одним дополнительным полем в узле, которое является макс. Он работает довольно хорошо иногда, но на больших примерах у моих узлов возникает неправильный элемент max. Что я сделал не так ?Максимальный элемент. Алгоритм
public class Stack
{
public class Node
{
long data;
long max;
Node next;
}
Node head = null;
public void push(long data)
{
if(head == null)
{
head = new Node();
head.next = null;
head.data = data;
head.max = data;
return;
}
Node current = head;
while(current.next != null)
current = current.next;
Node temp = new Node();
temp.next = null;
temp.data = data;
if(current.data > temp.data)
{
temp.max = current.data;
}else
{
temp.max = data;
}
current.next = temp;
}
public void pop()
{
if(head == null)
return;
if(head.next == null)
{
head = null;
return;
}
Node current = head;
while(current.next.next != null)
current = current.next;
current.next = null;
}
public long getMax()
{
if(head == null)
return -1;
Node current = head;
while(current.next != null)
current = current.next;
return current.max;
}
}
Ваш pop-метод не обновляет максимальное поле. – Paul
Что вы сделали, чтобы попытаться решить проблему самостоятельно? – Qix