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
???
}
}
PHP linked list node swapping
Moderator: General Moderators
-
thelordofcheese
- Forum Newbie
- Posts: 2
- Joined: Wed Jul 23, 2008 10:37 am
Re: PHP linked list node swapping
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.
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
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
???
}
}
- EverLearning
- Forum Contributor
- Posts: 282
- Joined: Sat Feb 23, 2008 3:49 am
- Location: Niš, Serbia
Re: PHP linked list node swapping
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());
}