- import java.util.Stack;
- public class Reverse{
- class LNode{
- int data;
- LNode next;
- public LNode(int data){
- this.data=data;
- }
- }
- public static void main(String []args){
- Reverse r = new Reverse();
- for(int i=1;i<=10;i++){
- r.add(i);
- }
- // r.print(r.head);
- r.reverseLink(r.head);
- }
- LNode head;
- LNode current;
- Stack<Integer> s = new Stack<Integer>();
- // 通过栈的方式实现
- // public void reverseLink(LNode node){
- // current = node;
- // while(current!=null){
- // s.push(current.data);
- // current=current.next;
- // }
- // while(!s.empty()){
- // system.out.println(s.pop());
- // }
- // }
- // 递归实现
- public void reverseLink(LNode node){
- if(node!=null){
- if(node.next!=null){
- reverseLink(node.next);
- }
- System.out.println(node.data);
- }
- }
- public void add(int i){
- if(head==null){
- head=new LNode(i);
- current = head;
- }else{
- current.next=new LNode(i);
- current = current.next;
- }
- }
- public void print(LNode node){
- if(node==null) return;
- current = node;
- while(current!=null){
- System.out.println(current.data);
- current=current.next;
- }
- }
- }
注: 既然想到了用栈来实现这个函数, 而递归在本质上就是一个栈结构, 于是很自然地又想到了用递归来实现. 要实现反过来输出链表, 我们每访问到一个节点的时候, 先递归输出它后面的节点, 再输出该节点自身, 这样链表的输出结果就反过来了.
单链表翻转
来源: http://www.bubuko.com/infodetail-2643530.html