单链表翻转

本文介绍了一种使用递归方式实现链表逆序输出的方法。通过先递归访问链表尾部节点,再依次向前访问并输出每个节点,最终达到链表逆序输出的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
         }
     }
}

注:既然想到了用栈来实现这个函数,而递归在本质上就是一个栈结构,于是很自然地又想到了用递归来实现。要实现反过来输出链表,我们每访问到一个节点的时候,先递归输出它后面的节点,再输出该节点自身,这样链表的输出结果就反过来了。

转载于:https://www.cnblogs.com/yingpu/p/9181013.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值