Page 1 of 1

PHP linked list node swapping

Posted: Wed Jul 23, 2008 10:44 am
by thelordofcheese
I need some help getting two nodes in a linked list swapped. Here's the code:

class Node {
private $prev;
private $next;
private $value;
private $row;

function Node($value = null, $row = null){
$this->value = &$value;
$this->row = &$row;
}

function setPrev($node){
$this->prev = &$node;
}
function setNext($node){
$this->next = &$node;
}

function &getPrev(){
return $this->prev;
}
function &getNext(){
return $this->next;
}

...
}

class NodeList {
private $first;//head
private $last;//tail
private $size;

function NodeList(){
$this->first = new Node();
$this->last = new Node();
$this->size = 0;
}

function addNode($value,$row){
//this works fine
...
}

function swap($nodeA, $nodeB){
//switch the next and prev references between the parameters
???
}
}

Re: PHP linked list node swapping

Posted: Wed Jul 23, 2008 10:48 am
by JB4
Edit your post and put {code=php] before the code and {/code] after the code. But instead of using { use [

I can't really help you, but I know that makes people happy when you do that.

Re: PHP linked list node swapping

Posted: Wed Jul 23, 2008 11:00 am
by thelordofcheese

Code: Select all

 
class Node {
  private $prev;
  private $next;
  private $value;
  private $row;
 
  function Node($value = null, $row = null){
    $this->value = &$value;
    $this->row = &$row;
  }
 
  function setPrev($node){
    $this->prev = &$node;
  }
  function setNext($node){
    $this->next = &$node;
  }
 
  function &getPrev(){
    return $this->prev;
  }
  function &getNext(){
    return $this->next;
  }
 
  ...
}
 
class NodeList {
  private $first;//head
  private $last;//tail
  private $size;
 
  function NodeList(){
    $this->first = new Node();
    $this->last = new Node();
    $this->size = 0;
  }
 
  function addNode($value,$row){
    //this works fine
    ...
  }
 
  function swap($nodeA, $nodeB){
    //switch the next and prev references between the parameters
    ???
  }
}
 

Re: PHP linked list node swapping

Posted: Wed Jul 23, 2008 11:27 am
by EverLearning
Try this(untested):

Code: Select all

function swap($nodeA, $nodeB){
    $tempNodeA = clone $nodeA;
    $tempNodeB = clone $nodeB;
 
    $nodeB->setPrev($tempNodeA->getPrev());
    $nodeB->setNext($nodeA);
 
    $nodeA->setPrev($nodeB);
    $nodeA->setNext($tempNodeB->getNext());
}