Home > database >  Add element to listnode in PHP
Add element to listnode in PHP

Time:12-29

If i have a listnode with the following defination

class ListNode {
      public $val = 0;
      public $next = null;
      function __construct($val = 0, $next = null) {
          $this->val = $val;
          $this->next = $next;
      }
  }

How can i add an element to the end of the listnode and thus add int[i] elements by interation?

CodePudding user response:

class ListNode {

  public int $val = 0;
  public ?ListNode $next = null;

  function __construct(?int $val = 0, ?ListNode $next = null) {
    $this->val = $val;
    $this->next = $next;
  }

  function appendToListEnd(int $val) {
    if ($this->next == null) {
      $this->next = new ListNode($val);
    } else {
      $temp = $this->next;
      while ($temp->next != null) {
        $temp = $temp->next;
      }
      $temp->next = new ListNode($val);
    }
  }

}

$arr = [ 1, 2, 3, 4 ];

$listHead = new ListNode($arr[0]);

for ($i = 1; $i < count($arr); $i  ) {
  $listHead->appendToListEnd($arr[$i]);
}
print_r($listHead);

$listHead->appendToListEnd(5);
print_r($listHead);
  • Related