2011-09-09 3 views
0

내가 지금 내가 그것을 원형을하고자 PHP 에서 하나의 LinkedList의를 만들었습니다, 어떤 도움이 정말 LinkedList의PHP에서 순환 링크 된 목록을 만드는 방법?

class listNode{ 


    public $data; 
    public $next; 

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


class linkedList { 

    public $firstNode; 

    public $lastNode; 

    public $link; 





    public function __construct() 
    { 
     $this->firstNode = NULL; 
     $this->lastNode = NULL; 
     $this->link=NULL; 
    } 

    public function insertFirst($data) 
    { 


     $tempStore=new listNode($data); 
     $this->firstNode=clone($tempStore); 
     $tempStore->next=$this->link; 

     $this->link=$tempStore; 


     if($this->lastNode == NULL){ 
      $this->lastNode = $this->link; 
      } 

    } 

    public function insertLast($data) 
    { 

     if($this->firstNode==null) 
     { 
      $this->insertFirst($data); 
     }else{ 
      $tempStore=new listNode($data); 
      $this->lastNode->next=$tempStore; 

      print_r($this->lastNode); 
      $this->lastNode=$tempStore; 
      print_r($this->lastNode); 

     } 

    } 


    public function makeCircular() 
    { 



    } 
} 




$totalNodes=5; 

$theList = new linkedList(); 

for($i=1; $i <= $totalNodes; $i++) 
{ 
    $theList->insertLast($i); 
} 


print_r($theList); 

LinkedList의 개체 ( [firstNode] => listNode 개체에 대한

코드를 감사 ( [데이터] => 1 [다음] => )

[lastNode] => listNode Object 
    (
     [data] => 5 
     [next] => 
    ) 

[link] => listNode Object 
    (
     [data] => 1 
     [next] => listNode Object 
      (
       [data] => 2 
       [next] => listNode Object 
        (
         [data] => 3 
         [next] => listNode Object 
          (
           [data] => 4 
           [next] => listNode Object 
            (
             [data] => 5 
             [next] => 
            ) 

          ) 

        ) 

      ) 

    ) 
,745

$this->lastNode->next = $this->firstNode; 

: 코드가 제대로 작동하고 원형 만들기, 연결리스트에 대한 올바른 데이터 구조를 기반으로 가정

)

+0

PHP는 이미 배열을 지원하며, 배열을 조작하기위한 여러 가지 기능을 제공합니다. 연결된 목록 (예 : 숙제)을 구현하려는 특별한 이유가 있습니까? – duskwuff

+0

Iam은 이것을 가내 노동으로하고 있습니다. –

답변

2

는 예를 들어, 첫 번째 노드에 마지막 노드 점을 단지 문제입니다 insertFirst 또는 insertLast과 함께 더 많은 노드를 추가 할 때이 링크가 유지되는지 확인해야합니다. 즉, 처음/마지막 노드를 새로 삽입 할 때 항상 lastNode->next = firstNode을 설정하십시오.

관련 문제