Menu
CoddyTech

最终挑战:移植队列模型

Coddy 面向 C# 开发者的 PHP 课程的第 48 课,共 48 课。

challenge icon

挑战

简单

输入为 [initial,operations]。移植本挑战中提供的源程序参考实现。WorkQueue(initial array) 用于存储字符串项。push(string):void 会追加项;pop():?string 会移除并返回最早添加的项,队列为空时返回 null;size():int 用于统计剩余项数。操作为 [push,text] 或 [pop]。驱动程序会输出弹出的值,各值之间用逗号分隔;如果值为 null,则使用 EMPTY,随后输出 |size。输入项仅包含 ASCII 字母。

提供的主脚本会从标准输入读取一个 JSON 值,检查指定的公共 API,并输出结果。实现模块声明,不要打印内容;不要替换启动程序,也不要从模块读取输入。输入符合指定的类型和范围。

编辑 WorkQueue.php。main.php 是锁定的入口文件。依赖项使用 require_once __DIR__ 和相对文件名。

C# 参考程序

#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;

class Program {
class WorkQueue{
 private readonly Queue<string> items;
 public WorkQueue(IEnumerable<string> initial){items=new Queue<string>(initial);}
 public void Push(string item){items.Enqueue(item);}
 public string? Pop(){return items.Count==0?null:items.Dequeue();}
 public int Size(){return items.Count;}
}
 static void Main() {
  var q=new WorkQueue(new[]{"a","b"});var output=new List<string?>{q.Pop()};q.Push("c");output.Add(q.Pop());Console.WriteLine(string.Join(",",output)+"|"+q.Size());
 }
}

亲手试试

<?php
declare(strict_types=1);
require_once __DIR__."/WorkQueue.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
function queueReport(array $i):string{$q=new WorkQueue($i[0]);$out=[];foreach($i[1] as $op){if($op[0]==="push")$q->push($op[1]);else $out[]=$q->pop()??"EMPTY";}return implode(",",$out)."|".$q->size();}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
$a=new WorkQueue(["a"]);$b=new WorkQueue([]);ensure($a->pop()==="a" && $a->pop()===null && $b->size()===0,"queue independence");$a->push("z");ensure($a->size()===1 && $a->pop()==="z","queue API");
echo queueReport($input),"\n";

面向 C# 开发者的 PHP中的所有课

自己练习: PHP 在线编译器