【问题标题】:Creating node inside a method在方法中创建节点
【发布时间】:2015-11-12 03:55:53
【问题描述】:

我正在尝试将此代码“转换”为将创建节点项的方法。我知道我必须使用 for 循环,但我想不出办法来完成这项工作。

原代码:

public class GenericLinkedListDemo
{
 public static void main(String[] args)
 {
 LinkedList3<Entry> list = new LinkedList3<Entry>( );
 Entry entry1 = new Entry(1);
 list.addToStart(entry1);
 Entry entry2 = new Entry(2);
 list.addToStart(entry2);
 Entry entry3 = new Entry(3);
 list.addToStart(entry3);

}

到目前为止,我所做的是在 GenericLinkedListDemo 中创建一个发送参数的方法:

public class GenericLinkedListDemo
    {
     public static void main(String[] args)
     {
     LinkedList3<Entry> list = new LinkedList3<Entry>( );
    addToList(list, 7);

我的方法:

public static void addToList(LinkMaster<Entry> L, int n){
        for (int i = n; i>0; i--) { 
            //This is where I want to put my "converted code"
        }
    }

我已经完成了创建节点(LinkMaster)的所有方法。我只是想知道如何使上面的这段代码以我只需要向代码发送参数的方式工作。

【问题讨论】:

  • addToList 应该做什么?您希望通过这种方法将什么添加到列表中?
  • 在原始代码中,我需要为要创建的每个节点输入条目(条目 1、条目 2、条目 3)。我想要的是一个 for 循环,它将进行相同的过程(创建节点)。

标签: java linked-list nodes


【解决方案1】:

我猜你想要这样的东西

public static void addToList(LinkMaster<Entry> list, int n){//here n will determine number of entry node to be added
        for (int i = n; i>0; i--) { 
            Entry entry = new Entry(i);
            list.addToStart(entry);
        }
    }

如果你通过 n = 7 ,那么 7 入口节点将被添加到列表中。

【讨论】:

  • 这正是我想要的。我进行了更改,eclipse 给了我以下消息:无法解析列表,并且局部变量列表可能未初始化。我整晚都在尝试这个。
猜你喜欢
  • 2017-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-18
  • 2022-06-15
  • 1970-01-01
  • 1970-01-01
  • 2020-09-26
相关资源
最近更新 更多