Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

java - Java:在链表中逐步添加元素(Java : add elements in linked list incrementally)

I'm working on a java project that adds nodes to the end of a linked list with int values .

(我正在研究一个Java项目,该项目将节点添加到具有int值的链表的末尾。)

However the nodes values must range between 0....n-1 inside the linked list .

(但是,节点值必须在链表内的0 .... n-1之间。)

I have already written code on how to append an element at the end of the list and check if an element already exists .

(我已经编写了有关如何在列表末尾添加元素并检查元素是否已存在的代码。)

The problem is how to add elements incrementally and start from 0 .

(问题是如何逐步添加元素并从0开始。)

ex.{} add 3 : error (you must add 0)

(例如{}加3:错误(您必须加0))
{0} add 2 : error (you must add 1) I have written code bellow :

({0}加2:错误(您必须加1)我已经写了下面的代码:)

 class ItemNode {

public int item;
public ItemNode next;

public ItemNode(int item) {
    this.item = item;
    this.next = null;
  }
}

class ItemsList {
private  int nbNodes;
private  ItemNode first;
private  ItemNode last;

public ItemsList() {
    this.first = null;
    this.last = null;
    this.nbNodes = 0;
}

public int size() { 

    return nbNodes; 

}


public  boolean empty() {

    return first == null; 

}

    public  int append(int item) {

    ItemNode node = new ItemNode(item);

    if(this.empty())
    {
        first=node;
        last=node;
        nbNodes++;

    }

    else if (member(this.first,node.item))
    {
        System.out.println("Node already exists ");
    }

    else
    {
        last.next=node;
        last=node;
        nbNodes++;

    }




    return nbNodes;
}
  ask by user12437216 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

simply nbNodes will act as "whose turn is this" for example, if the list is empty, then nbNodes equals zero, means the element that should come next is zero, if the nbNodes equals five, then the next element should be five and so on.

(例如,如果列表为空,则nbNodes会简单地充当“此轮到谁”,那么nbNodes等于零,意味着下一步应该是零,如果nbNodes等于五,那么下一个元素应该是五,因此上。)

so the process is to check in the append method if the coming number equals nbNodes or not and act based on that.

(因此,该过程将检查append方法中即将出现的数字是否等于nbNodes并根据该数字进行操作。)

you may consider changing it's name to suite it's responsibility now, or add a new one for this task.

(您可以考虑立即更改其名称以适合其职责,或为此任务添加一个新名称。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...