简体   繁体   English

Java - 从链接列表中删除项目

[英]Java - Remove Items From Linked List

I have the following java class with constructor and getters and setters.我有以下 java class 与构造函数和获取器和设置器。

public class Train implements Comparable< Train >{
    private String power;      // "steam", "diesel" or "electric"
    private int numPassengers; // total number of passengers 
    private Wagon freight;     // linked list of freight wagons; does not include passenger carriages; 

    public String getPower() {
        return power;
    }
    public void setPower(String power) {
        this.power = power;
    }
    public int getNumPassengers() {
        return numPassengers;
    }
    public void setNumPassengers(int numPassengers) {
        this.numPassengers = numPassengers;
    }
    public Wagon getFreight() {
        return freight;
    }
    public void setFreight(Wagon freight) {
        this.freight = freight;
    }
    @Override
    public int compareTo(Train o) {
        return new Integer(this.getNumPassengers()).compareTo(new Integer(o.getNumPassengers()));
    }

    public Train(String power){
        setPower(power);
        setNumPassengers(0);
        setFreight(null);
    }

    public Train(String power, int pass){
        setPower(power);
        setNumPassengers(pass);
        setFreight(null);       
    }
}

And also another class, wagon which is used by the train class.还有另一个 class,火车 class 使用的货车。

class Wagon {
    private String cargo;   // e.g. "wheat"
    private int weight;     // weight of the cargo in tonnes
    private Wagon next;     // the wagon that follows this one in the train; or null if there isn't one

    public String getCargo() {
        return cargo;
    }

    public void setCargo(String cargo) {
        this.cargo = cargo;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    public Wagon getNext() {
        return next;
    }

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

    public Wagon(String cargo, int weight) {
        setCargo(cargo);
        setWeight(weight);
        setNext(null);
    }

    public Wagon(String cargo, int weight, Wagon next) {
        setCargo(cargo);
        setWeight(weight);
        setNext(next);
    }
}

I initialise a new train like so:我像这样初始化一列新火车:

Train trainC2 = new Train("steam", 0);
        trainC2.setFreight(new Wagon("wheat", 400, new Wagon("wheat", 300, new Wagon("maize", 280))));

I want to write a method that takes a train as an input, iterates through the wagons, if the cargo attribute matches a supplied string, the wagon is deleted.我想编写一个将火车作为输入的方法,遍历货车,如果货物属性与提供的字符串匹配,则删除货车。 I have written this method which creates a new linkedlist and adds the trains wagons to it.我已经编写了这个方法,它创建了一个新的链表并将火车车厢添加到其中。 It then iterates through this list and removes any matches.然后它遍历这个列表并删除任何匹配项。 I am trying to iterate again through the modified list and use the setFreight method to update the actual train object.我正在尝试再次遍历修改后的列表并使用 setFreight 方法来更新实际的火车 object。

    public static void removeWagons(Train train, String cargo) {
        LinkedList<Wagon> wag8 = new LinkedList<Wagon>();
        wag8.add(train.getFreight());
        ListIterator<Wagon> iter = wag8.listIterator();
        Wagon currentWagon = null;

        while (iter.hasNext()) {
            currentWagon = iter.next();
            System.out.println();

            if (currentWagon.getCargo() == cargo) {
                System.out.println("wag8b4" + wag8);
                iter.remove();
                System.out.println("wag8" + wag8);
                }

            }


        while (iter.hasNext()) {
            train.setFreight(iter.next());
} 

        }

I think I'm close, but don't know how to write a method that will produce an output like:我想我已经接近了,但不知道如何编写一个会产生 output 的方法,例如:

trainC2.setFreight(new Wagon("wheat", 400, new Wagon("wheat", 300, new Wagon("maize", 280))));

Or maybe there's a better way altogether?或者也许有更好的方法?

You are not iterating over Wagons because when you call wag8.add(train.getFreight()) , now your list has only one Wagon .您没有迭代 Wagons ,因为当您调用wag8.add(train.getFreight())时,现在您的列表只有一个Wagon My suggestion is to write a method named 'hasNext()' in your Wagon class so that you can know if there is another Wagon connected to the current wagon.我的建议是在您的Wagon class 中编写一个名为“hasNext()”的方法,这样您就可以知道是否有另一个Wagon连接到当前的 Wagon。 Something like this:像这样的东西:

public boolean hasNext(){
    return next!=null;
}

You seem to want to delete some wagons from the middle of the train.您似乎想从火车中间删除一些货车。 Let's say you want to delete the third wagon.假设您要删除第三辆货车。 For that, you can change the 'next' reference of the second wagon to point to the fourth wagon.为此,您可以将第二辆货车的“下一个”引用更改为指向第四辆货车。 Then you have no third wagon!那么你就没有第三辆马车了!

public static void removeWagons(Train train, String cargo) {
    // First we check the freight is not the matching wagon.
    // If it is we will ignore it
    Wagon freight = train.getFreight();
    Wagon currentWagon = train.getFreight();
    while(currentWagon.getCargo().equals(cargo)){
        freight= currentWagon.next;
        currentWagon=currentWagon.next;
    }
    //We make another wagon to hold a reference to the previous wagon
    Wagon previous=currentWagon;
    //Now the first wagon is alright. So "currentWagon" don't need to be the first
    currentWagon=currentWagon.next;
    
    do{
        if (currentWagon.getCargo().equals(cargo)){
            previous.next=currentWagon.next;
            currentWagon= currentWagon.next;
            continue;
        }
        previous= currentWagon;
        currentWagon= currentWagon.next;
            
    } while(currentWagon.hasNext())
    train.setFreight(freight);
}

Some parts of code are ambiguous.代码的某些部分是模棱两可的。 So don't hesitate to ask how does it work.所以不要犹豫,问它是如何工作的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM