1

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;
    }
}
}
2
  • Use an iterator or a for each loop. Commented Oct 29, 2014 at 6:40
  • Your second loop looks like it's going to throw a NullPointerException because it dereferences current, but the first loop will not exit until current is null. Commented Oct 29, 2014 at 6:41

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Is there any difference using either the while or for loop to print out the list.
@user3497437 I don't think so, since it's the same code written in two different ways.
3

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.

1 Comment

Thank. Its there a major difference using the while or for loop
0

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);
        }
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.