简体   繁体   中英

Displaying all elements in a LinkedList without ListIterator

I am having issues trying to figure out how to display all elements in a 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.

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?

A few examples how to loop through LinkedList in Java (including one you don't like - using 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. Here loop upto the position, get the data and return the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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