链表翻转循环和递归写法

链表翻转循环和递归写法

1.链表翻转循环实现原理图

在这里插入图片描述

2.节点定义

class Node
{
    public $e;//节点元素
    public $next; //下个节点信息

    /**
     * 构造函数 设置节点信息
     * Node constructor.
     * @param $e
     * @param $next
     */
    public function __construct($e, $next=null)
    {
        $this->e = $e;
        $this->next = $next;
    }
}

3.链表翻转循环实现代码

<?php
require 'LinkedList.php';

$linkedList = new LinkedList();

for ($i = 1;$i <= 20;$i++){
    $linkedList->addFirst($i);
}
echo $linkedList->toString();
/**
 * 20->19->18->17->16->15->14->13->12->11->10->9->8->7->6->5->4->3->2->1->null
 */
echo "\n";

function reverse($head){
    $pre = $head;
    $cur = $head->next;
    while ($cur){
        $next = $cur->next;
        $cur->next = $pre;
        $pre = $cur;
        $cur = $next;
    }
    $head->next = null;

    return $pre;
}

$linkedList->setHead(reverse($linkedList->getHead()));


echo $linkedList->toString();
/**
 * 1->2->3->4->5->6->7->8->9->10->11->12->13->14->15->16->17->18->19->20->null
 */
echo "\n";

演示输出如下图:
在这里插入图片描述

4.链表翻转递归实现思想步骤和原理图

  • 画图分析
  • 将递归函数当成整体,不要跳进递归里边(因为你的脑袋压栈不了几个)
  • 写代码先处理递归到底的情况
    在这里插入图片描述

5.递归代码

    public function recursionLinkedList(){
        $this->head = $this->recursion($this->head);
    }

    private function recursion($head){
        if($head->next == null){
            return $head;
        }

        $cur = $head;
        $next = $this->recursion($head->next);//这个想象成一个已经翻转的链表其返回值是头
        $head->next->next = $head;//需要得到递归整体链表的尾部,有一种low办法就是遍历,但在这里可以直接取 $head节点的 next 节点,因为其指向的地址没有变
        $head->next = null;//原来的头需要指向null

        return $next;//最后需要返回递归整体这个链表
    }

演示输出如下图:
在这里插入图片描述

Tips:代码仓库:https://gitee.com/love-for-poetry/arithmetichttps://gitee.com/love-for-poetry/data-structure

扫码关注
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值