Java:增量添加链表中的元素 [英] Java : add elements in linked list incrementally

查看:24
本文介绍了Java:增量添加链表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 Java 项目,该项目将节点添加到具有 int 值的链表的末尾.然而,节点值必须在链表内的 0....n-1 之间.我已经编写了关于如何在列表末尾附加元素并检查元素是否已存在的代码.问题是如何增量添加元素,从0开始.

I'm working on a java project that adds nodes to the end of a linked list with int values . However the nodes values must range between 0....n-1 inside the linked list . 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 .

例如{}添加 3:错误(您必须添加 0)
{0} 添加 2 :错误(您必须添加 1)我已经编写了以下代码:

ex.{} add 3 : error (you must add 0)
{0} add 2 : error (you must add 1) I have written code bellow :

 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;
}

推荐答案

只是 nbNodes 将充当轮到谁了"例如,如果列表为空,则 nbNodes 等于 0,表示下一个应该是 0 的元素,如果 nbNodes 等于 5,则下一个元素应该是 5,以此类推.

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.

所以过程是检查 append 方法是否等于 nbNodes 并根据它采取行动.

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

您可以考虑更改它的名称以适应它现在的职责,或者为此任务添加一个新名称.

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

这篇关于Java:增量添加链表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆