簡體   English   中英

如果列表中的最后一個元素大於其他元素,該如何刪除?

[英]How to delete last element from List if it's bigger than other ones?

我在這里需要有關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);
}
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

我對您索引的第一個和最后一個元素有點困惑,但這就是答案

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM