[英]printing a linked list using for loop in java
我正在學習鏈表,並編寫了示例代碼以了解基本原理。 我的代碼可以工作,但是還有另一種使用for循環而不使用while循環來打印列表的方法嗎?
我使用了for循環作弊,因為我已經知道列表中的節點數。 是否有使用for循環打印列表的其他方法?
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;
}
}
}
您可以這樣操作:
for (FriendNode current=g; current != null; current = current.next) {
System.out.println(current);
}
假設g
是第一個節點,因為這是您在使用while循環打印列表時初始化current
。
除了將初始化和增量移至for
表達式(使其更緊湊)外,它基本上與while循環相同。
for循環不必只與int一起工作,也不必遞增或遞減。 這也是有效的:
for (FriendNode ii = g; ii != null; ii = ii.next)
{
System.out.println(ii);
}
但是,兩者的潛在問題是存在無限循環的風險-如果將m.next設置為g,則while循環和for循環都將永遠執行。 如果需要,可以通過保留對您剛開始使用的FriendNode(g)的引用並在i為g的情況下跳出循環來避免此情況。
您可以實現Iterable並使用“另一種” for循環
for (Friend f : new FriendList(g)) {
System.out.println(f.name);
}
我創建了一個FriendList
使用的FriendNode
。 並將Friend
對象卡在FriendNode
內,而不僅僅是一個字符串。 IMO,這將使您擁有更好的可擴展性。
實現看起來像這樣:
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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.