当前位置: 首页 > 后端技术 > PHP

5.数据结构(PHP实现)--集合(链表实现)

时间:2023-03-29 15:41:48 PHP

1、特征集中的元素不会重复,所以添加的时候需要判断是否有元素。2.时间复杂度分析操作时间复杂度AddO(1)DeleteO(n)QueryO(n)3。代码元素节点/***内容:集合的元素节点*create:2020-11-03*/setTail($tail)->setValue($value);}/***设置尾节点*@paramNode|null$tail*@return$this*/publicfunctionsetTail(?Node$tail):self{$this->tail=$tail;返回$这个;}/***获取尾节点*@returnNode|null*/publicfunctiongetTail():?Node{return$this->tail;}/***设置值*@parammixed$value*@return$this*/publicfunctionsetValue($value):self{$this->value=$value;返回$这个;}/***获取节点中的值*@returnmixed*/publicfunctiongetValue(){return$this->value;}}集合代码node=null;$这个->大小=0;}/***获取集合中的元素*@returnint*/publicfunctiongetSize():int{return$this->size;}/***查询是否有这个值的节点*@param$value*@returnNode|null*/publicfunctioncontains($value):?Node{$node=$this->node;while(!is_null($node)){if($node->getValue()===$value){返回$node;}$node=$node->getTail();}返回空值;}/***Insert*@paramstring|int$value*@returnNode*@throws\Exception*/publicfunctionadd($value):Node{$newNode=newNode($value,null);如果(is_null($this->node)){$this->node=$newNode;}else{if(!is_null($this->contains($value))){thrownew\Exception('插入的元素已经存在!');}$newNode->setTail($this->node);$this->node=$newNode;}$this->size++;返回$新节点;}/***delete*@param$value*/publicfunctionremove($value){//如果图中没有元素,则返回if(is_null($this->node))return;//如果第一个节点被删除if($this->node->getKey()==$key){$this->node=$this->node->getTail();$这个->大小--;返回;}//删除第二个及之后的节点$node=$this->node;while(!is_null($node->getTail())){如果($node->getTail()->getKey()===$key){$node->setTail($node->getTail()->getTail());$这个->大小--;返回;}$node=$node->getTail();}返回;}publicfunctionvarDump(){$node=$this->node;while(!is_null($node)){echo$node->getValue().PHP_EOL;$node=$node->getTail();}}}4。示例add(1);$set->add(2);$set->add(3);$set->add(4);$set->add(5);$set->add(6);$set->varDump();654321