【问题标题】:creating x amount of elements in a link list在链接列表中创建 x 个元素
【发布时间】:2012-12-03 05:42:44
【问题描述】:

我的任务是制作一个包含 5, 7, 3,5, 7, 3 元素且 5, 7, 3 重复 100 次的链接列表

IntNode first = new IntNode() ;
first.value = 5 ; //first -> 5
first.next = new IntNode() ;
first.next.value = 7 ; //first -> 5 -> 7
first.next.next.next = new IntNode() ;
first.next.next.next.value = 3 ; 

除了继续添加重复元素下 x 次之外,有什么方法可以使用循环来创建链接列表。

【问题讨论】:

  • 我相信你的老师提到了一些关于循环的事情,不是吗?
  • 我相信当他们谈到链表时,他们也谈到了如何保持一个遍历链表的指针。
  • 以下链接对你有帮助stackoverflow.com/questions/5236486/…
  • @gresdiplitude:是否是家庭作业并不重要......无论如何,要回答这个问题,,可以使用循环。追问:你的LinkedList 类中是否有任何insert() 方法?这是一个非常大的暗示。 ;)

标签: java linked-list


【解决方案1】:

试试这个方法:

    // IntNode first = new IntNode();
    // first.value = 5; // first -> 5
    // first.next = new IntNode();
    // first.next.value = 7; // first -> 5 -> 7
    // first.next.next.next = new IntNode();
    // first.next.next.next.value = 3;
    int values[] = { 5, 7, 3 };     
    IntNode first = new IntNode();

    for (int i = 0; i < 100; i++) {
        IntNode temp = new IntNode();
        temp.value = values[i % 3];
        temp.next = new IntNode();
        first.next = temp;
        first = first.next;
    }

【讨论】:

    猜你喜欢
    • 2022-12-04
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多