链表的倒序遍历,我们很容易想到,利用栈来存储,再输出
public void reversePrint(){
Stack<Node> stack=new Stack<Node>();
Node p=head;
while(p!=null){
stack.push(p);
p=p.next;
}
while(!stack.isEmpty()){
System.out.println(stack.pop().data);
}
}
但是我们也可以利用递归的思想
public void reversePrint02(Node p){
if(p!=null){
reversePrint02(p.next);
System.out.print(p.data+" ");;
}
}
对于链表的逆置,在面试过程中也是经常考的
public Node Inverse(){
Node p1=head;
Node p2=p1.next;
Node p3=null;
while(p2!=null){
p3=p2.next;
p2.next=p1;
p1=p2;
p2=p3;
}
head.next=null;
head=p1;
return head;
}