zoukankan      html  css  js  c++  java
  • 编程11:打印两个有序链表的公共部分

    <?php
    header("content-type:text/html;charset=utf-8");
    /*
     *打印两个有序链表的公共部分 P34
     * 注意是有序链表哦!!!
     */
    class Node{
        public $value;
        public $next;
        public function __construct($value){
            $this->value = $value;
        }
    
    }
    
    function printCommonPrint(Node $head1,Node $head2){
        while ($head1 != null && $head2!= null){
            if($head1->value < $head2->value){
                $head1 = $head1->next;
            }
            elseif ($head1->value > $head2->value){
                $head2 = $head2->next;
            }
            else{
                echo $head1->value." ";
                $head1 = $head1->next;
                $head2 = $head2->next;
            }
        }
    }
    
    $head1 = new Node(1);
    $head1->next = new Node(3);
    $head1->next->next = new Node(5);
    $head1->next->next->next = new Node(7);
    $head1->next->next->next->next = new Node(9);
    $head1->next->next->next->next->next = new Node(10);
    $head1->next->next->next->next->next->next = new Node(11);
    $head1->next->next->next->next->next->next->next = new Node(12);
    
    $head2 = new Node(2);
    $head2->next = new Node(4);
    $head2->next->next = new Node(6);
    $head2->next->next->next = new Node(8);
    $head2->next->next->next->next = new Node(9);
    $head2->next->next->next->next->next = new Node(10);
    $head2->next->next->next->next->next->next = new Node(11);
    $head2->next->next->next->next->next->next->next = new Node(12);
    
    echo "链表1为:";
    echo "</br>";
    print_r($head1);
    echo "</br>";
    echo "</br>";
    
    echo "链表2为:";
    echo "</br>";
    print_r($head2);
    echo "</br>";
    echo "</br>";
    
    echo "两个链表的公共部分是:";
    echo "</br>";
    printCommonPrint($head1,$head2);

    输出结果:

  • 相关阅读:
    windows服务等获取文件路径文件目录方法
    推荐几款很棒的 JavaScript 表单美化和验证插件
    在网站制作中随时可用的10个 HTML5 代码片段
    SQLServer数据排序
    SQL Join的一些总结
    3.14(链表练习)
    链表
    基数排序
    hdu-1198(并查集)
    hdu-1207(规律推导)
  • 原文地址:https://www.cnblogs.com/xlzfdddd/p/10026772.html
Copyright © 2011-2022 走看看