CaitlinG CaitlinG - 1 month ago 19
Java Question

Iterating over a linked list in Java?

I have been diligently watching YouTube videos in an effort to understand linked lists before my fall classes start and I am uncertain how to proceed with iterating over the following linked list. The 'node' class is from a series of videos (same author), but the 'main' method was written by me. Am I approaching the design of a linked list in an illogical fashion (assuming of course one does not wish to use the predefined LinkedList class since the professor will expect each of us to write our own implementation)?:

class Node
{
private String data;
private Node next;

public Node(String data, Node next)
{
this.data = data;
this.next = next;
}

public String getData()
{
return data;
}

public Node getNext()
{
return next;
}

public void setData(String d)
{
data = d;
}

public void setNext(Node n)
{
next = n;
}

public static String getThird(Node list)
{
return list.getNext().getNext().getData();
}

public static void insertSecond(Node list, String s)
{
Node temp = new Node(s, list.getNext());
list.setNext(temp);
}

public static int size(Node list)
{
int count = 0;

while (list != null)
{
count++;
list = list.getNext();
}

return count;
}
}

public class LL2
{
public static void main(String[] args)
{
Node n4 = new Node("Tom", null);
Node n3 = new Node("Caitlin", n4);
Node n2 = new Node("Bob", n3);
Node n1 = new Node("Janet", n2);

}
}


Thanks for the help,

Caitlin

ug_ ug_
Answer

There are some flaws in your linked list as stated by some of the other comments. But you got a good start there that grasps the idea of a linked list and looks functional. To answer your base question of how to loop over this particular implemention of the linked list you do this

Node currentNode = n1; // start at your first node
while(currentNode != null) {
    // do logic, for now lets print the value of the node
    System.out.println(currentNode.getData());
    // proceed to get the next node in the chain and continue on our loop
    currentNode = currentNode.getNext();
}
Comments