
SplDoublyLinkedList::add 메서드는 두 번째 인자로 노드의 다음 노드를 받습니다. 이 경우 노드의 다음 노드가 이미 존재하는 노드일 경우, 새로운 노드를 기존 노드의 다음 노드로 설정합니다. 기존 노드의 이전 노드는 새로운 노드를 가리키게 됩니다.
예를 들어, 기존 노드 A가 존재하고, 새로운 노드 B가 추가되면 A의 다음 노드는 B가 됩니다. B의 이전 노드는 A가 됩니다.
#hostingforum.kr
php
class Node {
public $data;
public $prev;
public $next;
function __construct($data) {
$this->data = $data;
$this->prev = null;
$this->next = null;
}
}
class SplDoublyLinkedList {
public $head;
function __construct() {
$this->head = null;
}
function add($data, $nextNode = null) {
$node = new Node($data);
if ($this->head === null) {
$this->head = $node;
} else {
if ($nextNode !== null) {
$nextNode->prev = $node;
$node->next = $nextNode;
if ($this->head === $nextNode) {
$this->head = $node;
}
} else {
$node->next = $this->head;
$this->head->prev = $node;
$this->head = $node;
}
}
}
}
예제를 통해 SplDoublyLinkedList::add 메서드의 동작 방식을 이해할 수 있습니다.
2025-04-29 05:15