PHP linked list node swapping

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
thelordofcheese
Forum Newbie
Posts: 2
Joined: Wed Jul 23, 2008 10:37 am

PHP linked list node swapping

Post 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
???
}
}
JB4
Forum Commoner
Posts: 33
Joined: Tue Jul 22, 2008 6:07 pm
Location: Utah

Re: PHP linked list node swapping

Post 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.
thelordofcheese
Forum Newbie
Posts: 2
Joined: Wed Jul 23, 2008 10:37 am

Re: PHP linked list node swapping

Post 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
    ???
  }
}
 
User avatar
EverLearning
Forum Contributor
Posts: 282
Joined: Sat Feb 23, 2008 3:49 am
Location: Niš, Serbia

Re: PHP linked list node swapping

Post 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());
}
Post Reply