最大元素。算法

时间:2016-11-08 21:03:30

标签: java algorithm linked-list stack

我正在尝试从hackerrank解决最大元素任务。任务link 想法是通过链表实现Stack,节点中有一个额外的字段,即max。它有时很好用,但在更大的例子中,我的节点出错了max element。我做错了什么?

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;
}
}

1 个答案:

答案 0 :(得分:1)

您在下一行的推送中进行了错误的比较

if(current.data > temp.data) { temp.max = current.data; }else { temp.max = data; }

必须是

if(current.max > temp.data) { temp.max = current.max; }else { temp.max = data; }

在这里,您必须使用当前最大值检查推送值,如果新值大于那么它是最大值。否则,当前最大值也会在推送节点中保留其最大值贪婪