码迷,mamicode.com
首页 > 其他好文 > 详细

循环链表

时间:2019-12-24 11:51:32      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:nod   add   public   while   fun   添加   ==   dex   struct   

class Node{
		public $data=null;
 		public $next = null;
 		public function __construct($data=null){
 			$this->data = $data;
 		}
	}

	class LinkdList{
		public $header=null;
		public function __construct($data=null){
			$this->header= new Node();
		}
		//插入
		public function insert($data){
			$current = $this->header;
			$newNode = new Node($data);

			while($current->next){
				if($current->next != $this->header){
					$current = $current->next;
				}else{
					break;	
				}
			}
			$current->next = $newNode;
			$newNode->next = $this->header;
		}
		//查找所在位置
		public function find($data){
			$current = $this->header->next;
			$index=1;
			while($current){
				if($current->data == $data){
					break;
				}else{
					$index++;
					$current = $current->next;
				}
			}
			return $index;
		}

		//固定位置修改
		public function update($data,$num){
			$current = $this->header->next;
			$index=1;
			while($index < $num ){
				$current = $current->next;
				$index++;
			}
			$current->data=$data;
		}
		//添加
		public function add($data,$num){
			$current = $this->header->next;
			$index=1;
			$newNode = new Node($data);
			while($index < $num){
				$prev = $current;
				$current=$current->next;
				$index++;
			}
			$prev->next = $newNode;
			$newNode->next = $current;
		}

		//删除
		public function del($num){
			$current = $this->header->next;
			$index = 1;
			while($index < $num){
				$prev = $current;
				$current = $current->next;
				$index++;
			}
			$prev->next = $current->next;
		}

		//遍历
		public function listLink(){
            $current=$first = $this->header;
            while($current){
            	$current = $current->next;
            	if($current == $first){
            		break;
            	}
            	echo $current->data;
            	echo "\r\n";
            }
        }
	}

	//$arr=[10,304,4,5,1,30];
	$arr=[10,304,4,5,1,30,38];
    $obj  = new LinkdList();
    foreach ($arr as $key => $value) {
        $obj->insert($value);
    }
    //$obj->update(100,2);
    //$obj->add(90,4);
   //echo  $obj->find(5);
   $obj->del(4);
   $obj->listLink();

  

循环链表

标签:nod   add   public   while   fun   添加   ==   dex   struct   

原文地址:https://www.cnblogs.com/zh718594493/p/12090225.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!