gpt4 book ai didi

java - 如果列表中的最后一个元素比其他元素大,如何删除它?

转载 作者:行者123 更新时间:2023-12-02 11:06:14 25 4
gpt4 key购买 nike

我需要一些有关 Java 的帮助。我有一些类(class):

类节点:

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)列表:

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

关于java - 如果列表中的最后一个元素比其他元素大,如何删除它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50934000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com