我在使用链表程序时遇到了困难。我想编写一个方法,用列表尾部的值之和破坏性地替换每个节点 n 中的值。所以如果列表是2,3,5,7;我想将其更改为 17、15、12、7。我得到了一个程序,我必须在其中添加一个执行此操作的方法。我可以改变第一个数字,但我不能改变其他三个,我被卡住了。如果有人可以帮助我,那就太好了。
原创节目
public class IntList {
private int value;
private IntList next;
public IntList(int v, IntList n) { // Constructor
value = v;
next = n;
}
public int getValue() { return value; } // Getters
public IntList getNext() { return next; }
public void setValue(int v) { value = v; } // Setters
public void setNext(IntList n) { next = n; }
// Find the last node of a linked list.
public IntList findLast() {
if (getNext() == null) return this;
else return getNext().findLast();
}
// Add a new node with value v at the end of l;
public void addEnd(int v) {
findLast().setNext(new IntList(v,null));
}
// Add up the values in a list, recurring down the owner
public int sumList() {
if (getNext() == null) return getValue();
else return getValue() + getNext().sumList();
}
// Convert list of int to string
// Recursive method for constructing the end of the string, after the
// initial open bracket.
public String toString1() {
if (getNext() == null)
return getValue() + "]";
else return getValue() + ", " + getNext().toString1();
}
// Top level rountine that starts with the "[" and then calls toString1 to
// do the rest.
public String toString() {
return "[" + toString1();
}
// Recursive method for finding the sum of a list, using recursion down
// an argument. Note that this is a static method, associated with the class
// not with an object owner.
static public int sumListArg(IntList l) {
if (l==null) return 0;
else return l.getValue() + sumListArg(l.getNext());
}
static public void main(String[] args) {
IntList l = new IntList(2,null);
l.addEnd(3);
l.addEnd(5);
l.addEnd(7);
System.out.println("h");
System.out.println(l.toString());
System.out.println("Sum = " + l.sumList());
} // end main
} // end RecursiveIntList
这是我到目前为止的方法(我认为这在逻辑上是可以的,但它是不正确的):
public static void runningSum(IntList l)
{
l.setValue(l.sumList());
while(l.getNext() != null)
{
l.setNext(l.getNext()); //Set Next to be the next reference
l.getValue(); //Get the Next's value
l.setValue(l.sumList()); //Add the rest of the numbers together
}
if(l.getNext() == null)
{
l.setValue(l.getValue());
}
System.out.println(l.toString());
}