add a node to the end of a linked list in php

To add a new node to the end of a linked list in PHP, you need to follow these steps:

  1. Create a new node with the given data.
  2. Traverse the linked list until you reach the last node.
  3. Set the next of the last node to the new node.

Here's the code to accomplish this:

main.php
class Node {
  public $data;
  public $next;

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

class LinkedList {
  private $head;

  function __construct() {
      $this->head = NULL;
  }

  function addNode($data) {
      $newNode = new Node($data);

      if($this->head === NULL) {
          $this->head = $newNode;
      } else {
          $current = $this->head;
          while($current->next !== NULL) {
              $current = $current->next;
          }
          $current->next = $newNode;
      }
  }
}
559 chars
32 lines

First, we define the Node class with a constructor that initializes the data property and sets next to NULL.

Next, we define the LinkedList class with a constructor that initializes the head property to NULL.

The addNode method takes data as input, creates a new Node with that data, and adds it to the end of the list.

If the list is empty, the new node becomes the head.

If the list is not empty, we traverse the list until we reach the last node. The last node points to NULL, so when we reach it, we simply set its next property to the new node.

To add a node to the end of the list, you can simply call the addNode method on the linked list object, passing in the data you want to add as a parameter.

gistlibby LogSnag