Java:在链表中逐步添加元素 [英] Java : add elements in linked list incrementally

查看:345
本文介绍了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等于零,这意味着下一个应为零的元素,如果nbNodes等于五,则下一个元素应为五,依此类推.

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天全站免登陆