如果列表中的最后一个元素大于其他元素,该如何删除?

时间:2018-06-19 17:33:06

标签: java list nodes

我在这里需要一些Java帮助。 我有一些课程:

类节点:

class Node{
    private int elem;
    private Node next;

    public Node(int elem, Node next){
        this.elem = elem;
        this.next = next;
    }

    public int getElem(){
        return elem;
    }

    public void setElem(int elem){
        this.elem = elem;
    }

    public Node getNext(){
        return next;
    }

    public void setNext(Node next){
        this.next = next;
    }
}

班级列表:

class List{
    private Node first;

    public List(){
        this.first = null;
    }

    public void insert(int elem){
        this.first = new Node(elem, first);
    }

    public String toString(){
        String s = "";
        for (Node p = first; p != null; p = p.getNext()) {
            if (p != first) s += ", ";
        s += p.getElem();
        }
    return s;
    }

    public void pushSum(){
        int sum = 0;
        Node p = first;
        while(p != null){
            sum += p.getElem();
            p = p.getNext();
        }
        this.insert(sum);
    }
}

让我们谈谈pushSum()方法,例如: 该方法应该在列表的开头插入所有元素的和。 输入示例:

1 2 3 4 5

pushSum()之后的示例输出

15 1 2 3 4 5

现在,我需要知道如何实现一种方法,如果该元素大于所有其他元素,则该方法将从列表中删除最后一个元素。 你们能帮我吗? 谢谢

public static void main(String[] args) {
    List l = new List();
    l.insert(0); // this is the first pushed element. but in tree this will be the last element
    l.insert(2);
    l.insert(3);
    l.insert(5);
    l.insert(100); // this is the last pushed element but this will be the first element in the tree

    System.out.println(l);
    l.pushSum();
    System.out.println(l);
}

2 个答案:

答案 0 :(得分:1)

public void removeLastIfLargest() {
    if (first == null)          // No elements
        return;
    if (first.getNext() == null) { // First element is alone and hence largest.
        first = null; // remove this line if you don't want this behaviour
        return;
    }
    Node n = first;
    Node p = null; // previous
    int largest = n.getElem();
    while(n.getNext() != null) {
        if (largest < n.getElem()) 
            largest = n.getElem();
        p = n;
        n = n.getNext();
    } 
    if (n.getElem() > largest)  // last is larger than previous largest
        p.setNext(null);
}

输出:

L: 1, 2, 3, 4, 5 // Before
L: 1, 2, 3, 4 // After

答案 1 :(得分:0)

您对第一个元素和最后一个元素的索引有点困惑,但这就是答案

public Node removeLast() {
    int val = first.getElem();

    for (Node p = first; p != null; p = p.getNext()) {
        if (p.getElem() > val) {
            return null;
        }
    }

    Node f = first;
    first = first.getNext();
    return f;
}

结果

input -> 1, 100, 3, 5, 101
output -> 1, 100, 3, 5

input -> 1, 100, 3, 5, 4
output -> 1, 100, 3, 5, 4