zoukankan      html  css  js  c++  java
  • 编程16:环形单链表的约瑟夫问题

    <?php
    header("content-type:text/html;charset=utf-8");
    /*
     *单链表的约瑟夫问题 P43
     */
    class Node{
        public $value;
        public $next;
        public function __construct($value)
        {
            $this->value = $value;
        }
    }
    
    function josephusKill1($head,$num){
        if($head == null || $head->next == null || $num == 0){
            return $head;
        }
    
        $last = $head;
        while ($last->next != $head){
            $last = $last->next;
        }
        $count = 0;
        while ($last != $head){
            if(++ $count == $num){
                $last->next = $head->next;
                $count = 0;
            }
            else{
                $last = $last->next;
            }
            $head = $last->next;
        }
        return $head;
    }
    
    function josephusKill2($head,$num){
        if($head == null || $head->next == null || $num == 0){
            return $head;
        }
    
        $cur = $head->next;
        $tem = 1;
    
        while ($cur != $head){
            $tem ++;
            $cur = $cur->next;
        }
        $tem = getLive($tem,$num);
        while (-- $tem != 0){
            $head = $head->next;
        }
        $head->next = $head;
        return $head;
    
    }
    
    function getLive($i,$num){
        if($i == 1){
            return 1;
        }
        return (getLive($i - 1,$num) + $num - 1) % $i +1;
    }
    
    $head1 = new Node(1);
    $head1->next = new Node(2);
    $head1->next->next = new Node(3);
    $head1->next->next->next = new Node(4);
    $head1->next->next->next->next = new Node(5);
    $head1->next->next->next->next->next = $head1;
    echo "初始循环列表为:";
    echo "</br>";
    print_r($head1);
    echo "</br>";
    echo "</br>";
    echo "方法1剩余结点为:";
    print_r(josephusKill1($head1,2));
    
    echo "</br>";
    $head2 = new Node(1);
    $head2->next = new Node(2);
    $head2->next->next = new Node(3);
    $head2->next->next->next = new Node(4);
    $head2->next->next->next->next = new Node(5);
    $head2->next->next->next->next->next = $head2;
    echo "方法2剩余结点为:";
    print_r(josephusKill2($head2,2));

    输出结果:

  • 相关阅读:
    在Windows环境下搭建redis
    三种主流的Web服务实现方案(REST+SOAP+XML-RPC)简述及比较
    ASP.NET Web API身份验证和授权
    quartz 设置时间格式
    服务端发post请求产生的编码问题
    大型网站的灵魂——性能
    大型网站系统架构的演化
    c# url自动解码解决方案
    C# RSA非对称加密实现
    .net上传图片之使用第三方平台七牛上传图片接口
  • 原文地址:https://www.cnblogs.com/xlzfdddd/p/10050331.html
Copyright © 2011-2022 走看看