一、问题描述:
百度面试题:逆序打印单链表
二、解决方案
1. 先反转,再遍历(破坏了结构)
逆序打印单链表
先将单链表反转,然后再遍历即可(不推荐)
代码如下:
//逆转单链表:
public static void reverseList(HeroNode head){
if(head.next == null || head.next.next == null){
return;
}
HeroNode quick = head.next; //快指针
HeroNode slow = null; //慢指针
while(quick != null){ //快指针不为空(没有结束)
HeroNode temp = quick.next; //保存快指针下个节点域
quick.next = slow; //逆置
slow = quick; //移动指针
quick = temp; //移动指针(取出来保存的)
}
head.next = slow;//头结点指向slow即可
}
//打印:
public static void printReverse(Node head){
if(head == null){
System.out.println("链表为空...");
return;
}
Node p = head.next;
while(p != null){
System.out.println(p);//调用Node类的toString()方法打印即可
}
p = p.next;
}
2. 利用“栈”逆序打印(推荐)
1. 定义一个栈来存储节点
2. 遍历链表,节点依次入栈
3. 出栈输出即可
如下图所示:
代码如下:
public static void print_reverse(HeroNode head){
if(head.next == null){
System.out.println("链表为空...");
return;
}
Stack<HeroNode> s = new Stack<HeroNode>();
HeroNode p = head.next;
while(p != null){
s.push(p);
p = p.next;
}
while(!s.empty()){
HeroNode cur = s.pop();
System.out.println(cur);
}
}