So I read several posts regarding this subject but they all refer to iterating through a linked list that is already implemented by Java; for example, LinkedList<String> list = new LinkedList<String>();
. And then goes on to say use a for loop to iterate through the linked list. However, I'm trying to implement my own linked list and I'm not sure how to iterate through them. In other words, I have the following code:
class Node {
private Node next = null;
private int data;
public Node(int d) {
data = d;
}
void appendToTail(int d) {
Node end = new Node(d);
Node n = this;
while(n.next != null) {
n = n.next;
}
n.next = end;
}
void print() {
Node n = this;
while(n.next != null) {
System.out.println(n);
n = n.next;
}
}
public static void main(String [] args) {
Node x = new Node(4);
x.appendToTail(5);
x.print();
}
}
The print()
function that I had written is my effort in trying to iterate through the linked list. But, it is not working. Anybody know how to iterate through the linked list, given your own implementation of the linked list?
Change
while(n.next != null)
to
while(n != null)
because inside the loop you are printing the current node n
and then pointing it to its next node by: n = n.next;
You should check whether current node is null
or not, not the next node. Because you will miss the last node of the list in that way, next
part will be null
for last node and loop would not execute.
You need to print data
part of the node. You have not defined the toString
method for your Node class.
void print() {
Node n = this;
while(n != null) {
System.out.println(n.data);
n = n.next;
}
}
You can define the toString
as below for your Node
class, then you can directly print the Node
object in System.out
statement.
@Override
public String toString() {
return "Node{" +
", data=" + data +
'}';
}
You should be checking n
for null, not n.next()
::
while(n != null)
but you have all the aspects of a for
loop (initial state, termination condition and iteration expression), so this can better be expressed as a for
loop:
for (Node n = this; n != null; n = n.next)
System.out.println(n.data);
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.