zoukankan      html  css  js  c++  java
  • 编程14:翻转单向和双向链表

    <?php
    header("content-type:text/html;charset=utf-8");
    /*
     *翻转单向和双向链表 P40
     */
    class SingleNode{
        public $value;
        public $next;
        public function __construct($value)
        {
            $this->value = $value;
        }
    }
    function reverseSingleList($head){
        if($head == null || $head->next == null){
            return $head;
        }
        $cur = $head;
        $pre = null;
        $next = null;
    
        while ($cur != null){
            $next = $cur->next;
            $cur->next = $pre;
            $pre = $cur;
            $cur = $next;
        }
        return $pre;
    }
    
    class DoubleNode{
        public $value;
        public $next;
        public $last;
        public function __construct($value)
        {
            $this->value = $value;
        }
    }
    
    function reverseDoubleList($head){
        if($head == null || $head->next == null){
            return $head;
        }
        $cur = $head;
        $pre = null;
        $next = null;
        while ($cur != null){
            $next = $cur->next;
            $cur->next = $pre;
            $cur->last = $next;
            $pre = $cur;
            $cur = $cur->next;
        }
        return $pre;
    }
    
    $head1 = new SingleNode(1);
    $head1->next = new SingleNode(3);
    $head1->next->next = new SingleNode(5);
    $head1->next->next->next = new SingleNode(7);
    $head1->next->next->next->next = new SingleNode(9);
    $head1->next->next->next->next->next = new SingleNode(11);
    
    echo "当前单链表为:";
    echo "</br>";
    print_r($head1);
    echo "</br>";
    echo "</br>";
    echo "翻转后的单链表为:";
    echo "</br>";
    print_r(reverseSingleList($head1));
    echo "</br>";
    echo "</br>";
    
    $head2 = new DoubleNode(1);
    $head2->last = null;
    $head2->next = new DoubleNode(3);
    $head2->next->last = $head2;
    $head2->next->next = new DoubleNode(5);
    $head2->next->next->last = $head2->next;
    $head2->next->next->next = new DoubleNode(7);
    $head2->next->next->next->last = $head2->next->next;
    $head2->next->next->next->next = null;
    
    
    echo "双向链表为:";
    echo "</br>";
    print_r($head2);
    echo "</br>";
    echo "</br>";
    echo "翻转后的双向链表为:";
    echo "</br>";
    print_r(reverseDoubleList($head2));

    实现结果:

  • 相关阅读:
    设计模式学习笔记--迭代器模式
    设计模式学习笔记--组合模式
    设计模式学习笔记--备忘录模式
    Asp.Net Core IdentityServer4 中的基本概念
    Asp.Net Core 中间件应用实践中你不知道的那些事
    Asp.Net Core Filter 深入浅出的那些事-AOP
    ASP.NET CORE 内置的IOC解读及使用
    ASP.NET CORE 管道模型及中间件使用解读
    ASP.NET CORE 启动过程及源码解读
    Linux +Docker +Nginx 部署代理转发初探
  • 原文地址:https://www.cnblogs.com/xlzfdddd/p/10039154.html
Copyright © 2011-2022 走看看