java linkedlist node 问题

a)createamethodcalledsuminclassNode(anyoftheNodeclassesthatwehavecreated),thatwillrec... a) create a method called sum in class Node (any of the Node classes that we have created), that will recursively calculate the sum of all of the int data values from that node to the last node in the list. (HINT: using the next pointer) This method should return (NOT PRINT OUT) the sum that was calculated.
b) IN CLASS LINKED LIST, create a method called sum that will take an int, n, as a parameter. It will call method sum (of class Node) on the nth node in the list. (the head is node 1, the node after head is 2, etc.) And then print out to a file the sum that was calculated. If the parameter passed is negative or zero, then the sum should be zero. If n is greater than the number of nodes in the list, then throw an appropriate exception.
我在class Node里面怎么怎么写sum method,才能在class linkedlist,里面用啊?因为Node里面的sum是计算全部的,而linkedlist里面是计算到第n个的,下面是Node 和linkedlist class,求各位学长大神教教我

publicclass Node {
privateintdata;
private Node next;
public Node(intd){
data = d;
}
public Node(intd, Node n){
data = d;
next = n;
}
publicint getData() {returndata; }
public Node getNext() {returnnext; }
publicvoid setNext(Node n) {next = n;}
}

publicclass LinkedList {

private Node head;
public LinkedList(Node n){
head =n;
}
public LinkedList(intx){
head = new Node(x);
}

publicvoid append(intx) {
Node current = head;
while (current.getNext()!=null){
current = current.getNext();
}
current.setNext(new Node(x));
}

publicvoid insert(intx) {
if(head.getData()>x){ //case 1: insert before head
head = new Node(x, head);
} else {
Node current = head;
Node previous = head;
while (current!=null){
if (current.getData()>x){ // case 2: insert into the middleof the list
previous.setNext(new Node(x, current));
// Node temp= new Node(x, current);
// previous.setNext(temp);
break;
} else {
previous = current;
current = current.getNext();
} // else
} // end ofwhile
if(current == null){ // case 3: insert after list
previous.setNext(new Node(x));
} // if
} // else
} // insertmethod

publicboolean delete(intx){
if(x==head.getData()){
head = head.getNext();
returntrue;
}
Node current = head;
Node previous = head;
while (current!=null){
if (current.getData()==x){ // case 2: delete from the middle or from the end
previous.setNext(current.getNext());
returntrue;
} elseif(current.getData()>x) {
returnfalse;
} else {
previous = current;
current = current.getNext();
}
}// while
returnfalse;
} // deletemethod
}
展开
 我来答
摩以旋4q
2014-08-03 · 超过13用户采纳过TA的回答
知道答主
回答量:46
采纳率:100%
帮助的人:18.1万
展开全部
你先建立一个属性int sum=0;直接在node构造器sum+=1;
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式