- 单向链表遍历,只能从前往后进行遍历
- 方法一:把链表的节点进行整体的反转,然后再遍历链表
public void printlnTest(Node head){
//调用链表中反转节点方法
Node head= LinkedList.opposite(head);
//遍历打印
Node temp=head.next;
//判断是否为空节点
if(temp==null){
return;
}
while(temp!=null){
System.out.println(temp.name);
}
}
- 方法二:遍历链表将节点的地址放入栈中利用栈数据结构的特性先进后出,进行逆序打印单向链表
public void printlnTest2(Node head){
//创建栈Stack数据结构
Stack<Node> stack=new Stack<Node>();
//判断是否为空链表
Node temp=head.next;
if(temp){
return;
}
//遍历链表,取出节点放入栈中
while(temp!=null){
stack.push(temp)
temp=temp.next;
}
//从栈中取出并输出 empty()判断是否为空栈
while(!stack.empty()){
Node temp2=stack.pop();
System.out.println(temp2.name);
}
}