分别通过迭代和递归算法实现链表反转

/**
 * 通过迭代、递归实现连表反转
 * @author :彭先生
 */
public class ChainReverse {

    @Data
    static class ChainNode{
        private String value;
        private ChainNode next;

        public ChainNode(String value, ChainNode next){
            this.value = value;
            this.next = next;
        }
    }

    /**
     * 迭代方式实现
     * @return
     */
    public static ChainNode iteration(ChainNode chainNode){
        //保存链边下一个指针
        ChainNode nextNode;
        //保存下一个节点的上一个指针
        ChainNode prevNode = null;
        //保存需要进行遍历的链表节点
        ChainNode thisNode = chainNode;
        while (thisNode != null) {
            nextNode = thisNode.next;
            thisNode.next = prevNode;
            prevNode = thisNode;
            thisNode = nextNode;
        }
        return prevNode;
    }

    /**
     * 递归方式实现
     * @return
     */
    public static ChainNode recursion(ChainNode chainNode){
        if(chainNode.next == null){
            return chainNode;
        }
        ChainNode recursion = recursion(chainNode.next);
        chainNode.next.next = chainNode;
        chainNode.next = null;
        return recursion;
    }

    public static void main(String[] args) {
        ChainNode chainNode1 = new ChainNode("1", null);
        ChainNode chainNode2 = new ChainNode("2", chainNode1);
        ChainNode chainNode3 = new ChainNode("3", chainNode2);
        ChainNode chainNode4 = new ChainNode("4", chainNode3);
        ChainNode chainNode5 = new ChainNode("5", chainNode4);
        /*  反转前默认是:5--->4--->3--->2--->1--->null   */
        System.out.println("链表反转前:" + chainNode5);

        /*  迭代反转后是:1--->2--->3--->4--->5--->null    */
        ChainNode iteration = iteration(chainNode5);
        System.out.println("使用迭代方式实现链表反转后:" + iteration);

        /*  递归再次反转后是:5--->4--->3--->2--->1--->null    */
        ChainNode recursion = recursion(iteration);
        System.out.println("使用递归方式实现链表反转后:" + recursion);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值