Skip to content
Advertisement

Add element to listnode in PHP

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?

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement