EI-01
EI-01

Reputation: 1095

printing a linked list using for loop in java

I am learning linked list and wrote a sample code to understand the fundamentals. My code works, but is there another way to print out the list using a for loop without the while loop?

I cheated using the for loop I made, because I already knew the number of nodes in the list. Is there a different way of printing the list using a for loop?

public class FriendNode {
FriendNode next;
String name;

FriendNode(String name)
{
    this.name = name;
    this.next = null;
}

public FriendNode(String name, FriendNode n)
{
    this.name = name;
    this.next = n;
}
public FriendNode getNext()
{
    return this.next;
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    FriendNode g = new FriendNode("Bob");
    FriendNode o = new FriendNode("Alice");
    FriendNode k = new FriendNode("Tom");
    FriendNode m = new FriendNode("Day");
    g.next = o;
    o.next = k;
    k.next = m;
    m.next = null;
    FriendNode current=g;
    while(current!=null)
    {
        System.out.println(current);
        current = current.next;
    }
    for(int i =0; i<4;i++)
    {
        System.out.println(current);
        current = current.next;
    }
}
}

Upvotes: 1

Views: 3375

Answers (3)

Michael Anderson
Michael Anderson

Reputation: 73470

You can implement Iterable and use "the other kind" of for loop

    for (Friend f : new FriendList(g)) {
        System.out.println(f.name);
    }

I've created a FriendList that uses the FriendNode. And stuck a Friend object inside the FriendNode rather than just a string. IMO that will allow you better extensiblity going forwards.

The implementation looks like this:

import FriendList.Friend;


public class FriendList implements Iterable<Friend> {

    public static class Friend {
        public Friend(String name) {
            this.name = name;
        }

        String name;
    }

    public static class FriendNode {
        FriendNode next;
        Friend friend;

        FriendNode(String name)
        {
            this.friend = new Friend(name);
            this.next = null;
        }

        public FriendNode(String name, FriendNode n)
        {
            this.friend = new Friend(name);
            this.next = n;
        }
        public FriendNode getNext()
        {
            return this.next;
        }
    }

    public FriendList(FriendNode n) {
        first = n;
    }

    @Override public Iterator<Friend> iterator() {
        return new Iterator<Friend>() {

            FriendNode node = first;

            @Override public boolean hasNext() {
                return node != null;
            }

            @Override public Friend next() {
                Friend f = node.friend;
                node = node.next;
                return f;
            }

            @Override public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    }

    FriendNode first;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        FriendNode g = new FriendNode("Bob");
        FriendNode o = new FriendNode("Alice");
        FriendNode k = new FriendNode("Tom");
        FriendNode m = new FriendNode("Day");
        g.next = o;
        o.next = k;
        k.next = m;
        m.next = null;

        FriendList list = new FriendList(g);

        for (Friend f : list) {
            System.out.println(f.name);
        }
    }

}

Upvotes: 0

furkle
furkle

Reputation: 5059

The for loop doesn't have to work purely with ints, nor does it have to be incremented or decremented. This is also valid:

for (FriendNode ii = g; ii != null; ii = ii.next)
{
    System.out.println(ii);
}

The potential problem with both, though, is that you run the risk of an infinite loop - if you set m.next to g, both the while loop and the for loop will execute forever. If you needed to, you could guard against that by keeping a reference to the FriendNode (g) you've started with, and breaking out of the loop if i is g.

Upvotes: 3

Eran
Eran

Reputation: 393771

You can do it this way :

for (FriendNode current=g; current != null; current = current.next) {
    System.out.println(current);
}

This is assuming that g is the first node, since that's how you initialized current when printing the list with the while loop.

It is essentially doing the same as the while loop, except that the initialization and increment are moved to the for expression, which make it more compact.

Upvotes: 3

Related Questions