我正在学习链表,这里有相关内容,但我有些困惑。我已经画出来了,但它们看起来仍然是相同的东西。
遍历链表:
遍历链表:
Node tmp = head;
while(tmp != null) {
tmp = tmp.next;
}
对于while循环的思路:tmp从头部开始。现在当tmp指向下一个节点时,tmp将继续指向其旁边的节点。并且这将一直进行,直到tmp没有指向其旁边的其他节点为止。
在链表末尾添加元素:
public void addLast(AnyType item)
{
if(head == null) addFirst(item);
else
{
Node<AnyType> tmp = head;
while(tmp.next != null)
tmp = tmp.next;
tmp.next = new Node<AnyType>(item, null);
}
}
对于while循环的思路:tmp从头开始。现在,当tmp指向下一个节点时,tmp会移动到指向其旁边的节点。这样一直进行,直到tmp没有指向另一个旁边的节点为止。然后它跳出循环并将tmp指向新节点的旁边。