思路:链表遍历是从头到尾,而打印需要从尾到头,再不更改链表的结构情况下,发现栈的“先入后出”特点正好符合要求。
//定义链表
public class ListNote {
private ListNote NextNote;
private int value;
public ListNote(){
}
public ListNote(int value){
this.value=value;
}
public ListNote getNext(){
return NextNote;
}
public void setNext(ListNote next){
this.NextNote=next;
}
public int getValue(){
return value;
}
public void setValue(int value){
this.value=value;
}
}
//从尾到头打印链表
public static void printRevers(ListNote headNote){
if(headNote==null){
return;
}
//引入一个栈
Stack<ListNote> stack=new Stack<ListNote>();
ListNote note=headNote;
while(note!=null){
stack.push(note);
note=note.getNext();
}
while(!stack.empty()){
System.out.println(stack.pop().getValue());
}
}