Home > Back-end >  How to remove a Node from Singly Linked List PHP
How to remove a Node from Singly Linked List PHP

Time:10-03

This is below a simple Class to create Singly Link List

class Node
{
   public $data;

   public $next;

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

I am adding new Node using below...

$e = new Node( 2, null );

$d = new Node( 15, $e );

$c = new Node( 9, $d );

$b = new Node( 4, $c );

$a = new Node( 3, $b );

When i print $a, it shows

Node Object
(
[data] => 3
[next] => Node Object
    (
        [data] => 4
        [next] => Node Object
            (
                [data] => 9
                [next] => Node Object
                    (
                        [data] => 15
                        [next] => Node Object
                            (
                                [data] => 2
                                [next] => 
                            )
                    )
            )
    )
)

which is correct! so now how do i delete a node based on it's value? such as odd or even?

if ( $node->data % 2 == 0 ) {}

the final result should be...

Node Object
(
[data] => 4
[next] => Node Object
    (
        [data] => 2
        [next] => 
    )

)

CodePudding user response:

You could define this method on your Node class:

   public function filter($callback) {
       $dummy = new Node(null, null);
       $tail = $dummy;
       $node = $this;
       while ($node != null) {
           if ($callback($node->data)) {
               $tail = $tail->next = $node;
           }
           $node = $node->next;
       }
       $tail->next = null;
       return $dummy->next;
   }

Then in your main program, you can do this:

$z = $a->filter(function ($data) {
    return $data % 2 == 0;
});

In your example case, $z will represent the list 4->2.

  • Related