简体   繁体   English

在没有ListIterator的情况下显示LinkedList中的所有元素

[英]Displaying all elements in a LinkedList without ListIterator

I am having issues trying to figure out how to display all elements in a LinkedList. 我在尝试弄清楚如何显示LinkedList中的所有元素时遇到问题。 I could solve this by having an arraylist to track the index of every element, however I would want to solve this without the use of arraylist or arrays. 我可以通过使用arraylist来跟踪每个元素的索引来解决此问题,但是我想解决此问题而不使用arraylist或arrays。

The following is what I currently have, 以下是我目前拥有的

public void displayItems()
    {
        ArrayList<Node> links = new ArrayList<Node>();
        links.add(head);
        for (int x = 0; x < count; x++)
        {
            links.add(links.get(x).getLink());
            System.out.println(links.get(x).getData());
        }

is there a way to display all elements, in a similar method as mentioned above but without the need for arrays or ListIterator? 有没有办法以与上述类似的方式显示所有元素,而不需要数组或ListIterator?

A few examples how to loop through LinkedList in Java (including one you don't like - using Iterator): 以下是一些如何在Java中遍历LinkedList的示例(包括您不喜欢的示例-使用Iterator):

LinkedList<Node> links = new LinkedList<Node>();
links.add(firstNode);
links.add(secondNode);
links.add(thirdNode);

/* For loop */
for(int i = 0; i < links.size(); i++) {
    System.out.println(links.get(i).getLink());
}

/* For-each loop */
for(Node node: links) {
    System.out.println(node.getLink());
}

/* While Loop*/
int i = 0;
while (links.size() > i) {
    System.out.println(links.get(i++).getLink());
}

/* Iterator */
Iterator<Node> it = links.iterator();
while (it.hasNext()) {
    System.out.println(it.next().getLink());
}

You can use an integer as a global variable, while inserting data into Linked List increment this variable. 您可以将整数用作全局变量,而在将数据插入“链表”时将其递增。

Write a method in LinkedList class with parameter position. 在LinkedList类中编写一个带有参数位置的方法。 Here loop upto the position, get the data and return the same. 在这里循环到该位置,获取数据并返回相同的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM