Implement linked list in php

后端 未结 8 697
小蘑菇
小蘑菇 2020-12-08 05:22

How should I implement a linked list in PHP? Is there a implementation built in into PHP?

I need to do a lot of insert and delete operations, and at same time I need

8条回答
  •  醉酒成梦
    2020-12-08 05:38

    I was also trying to write a program to create a linked list in PHP. Here is what I have written and it worked for me. I hope it helps to answer the question.

    Created a php file. Name: LinkedList.php
    {code}
    
    {code}
    
    This file is calling a class to create, insert and display nodes in linked list. Name: LinkedListNodeClass.php
    {code}
    data = $value;
        $obj->next = NULL;
      }    
    
      //Inserts a created node in the end of a linked list
      public function insertNodeInLinkedList($head, &$newNode) {
        $node = $head;
        while($node->next != NULL){
          $node = $node->next;
        }
        $node->next = $newNode;
      }
    
      //Inserts a created node in the start of a linked list
      public function insertNodeInHeadOfLinkedList(&$head, &$newNode) {
        $top = $head;
        $newNode->next = $top;
        $head = $newNode;
      }
    
      //Inserts a created node after a position of a linked list
      public function insertNodeAfterAPositionInLinkedList($head, $position, &$newNode) {
        $node = $head;
        $counter = 1;
        while ($counter < $position){
          $node = $node->next;
          $counter++;
        }
        $newNode->next = $node->next;
        $node->next = $newNode;
      }
    
      //Displays the Linked List
      public function displayLinkedList($head) {
        $node = $head;
        print($node->data); echo "\t";
        while($node->next != NULL){
          $node = $node->next;
          print($node->data); echo "\t";
        }
      }
    }
    
    ?>
    {code}
    

提交回复
热议问题