
SplDoublyLinkedList::valid 메서드는 Doubly Linked List의 유효성을 검사하는 메서드입니다. 유효성을 검사하는 과정에서 head와 tail 포인터가 null이 될 때, next와 prev 포인터가 null인 경우를 고려해야 합니다.
이러한 경우를 처리하는 방법은 두 가지 있습니다.
1. head와 tail 포인터가 null인 경우, next와 prev 포인터가 null인 경우 유효성을 검사하지 않습니다. 이는 Doubly Linked List가 비어 있는 경우에 해당합니다.
2. head와 tail 포인터가 null인 경우, next와 prev 포인터가 null이 아닌 경우 유효성을 검사하지 않습니다. 이는 Doubly Linked List의 head와 tail 포인터가 null인 경우, 노드의 next와 prev 포인터가 null이 아닌 경우에 해당합니다.
예를 들어, Doubly Linked List가 다음과 같이 구성되어 있다고 가정해 보겠습니다.
#hostingforum.kr
A -> B -> C -> D
이 경우, head 포인터는 노드 A를 가리키고, tail 포인터는 노드 D를 가리킵니다. next 포인터는 A -> B, B -> C, C -> D, D -> null을 가리키고, prev 포인터는 B -> A, C -> B, D -> C, null -> D를 가리킵니다.
이러한 경우, SplDoublyLinkedList::valid 메서드는 head와 tail 포인터가 올바른지 확인하고, next와 prev 포인터가 올바른지 확인합니다. head와 tail 포인터가 null인 경우, next와 prev 포인터가 null인 경우 유효성을 검사하지 않습니다.
#hostingforum.kr
php
class Node {
public $data;
public $next;
public $prev;
function __construct($data) {
$this->data = $data;
$this->next = null;
$this->prev = null;
}
}
class SplDoublyLinkedList {
public $head;
public $tail;
function __construct() {
$this->head = null;
$this->tail = null;
}
function valid() {
if ($this->head === null && $this->tail === null) {
return true; // Doubly Linked List가 비어 있는 경우
}
if ($this->head !== null && $this->tail !== null) {
// head 포인터가 올바른지 확인
if ($this->head->prev !== null || $this->head->data !== $this->head->prev->next->data) {
return false;
}
// tail 포인터가 올바른지 확인
if ($this->tail->next !== null || $this->tail->data !== $this->tail->next->prev->data) {
return false;
}
// next 포인터가 올바른지 확인
$current = $this->head;
while ($current->next !== null) {
if ($current->data !== $current->next->prev->data) {
return false;
}
$current = $current->next;
}
// prev 포인터가 올바른지 확인
$current = $this->tail;
while ($current->prev !== null) {
if ($current->data !== $current->prev->next->data) {
return false;
}
$current = $current->prev;
}
return true;
}
return false;
}
}
위의 예제 코드에서는 SplDoublyLinkedList::valid 메서드를 구현하여 Doubly Linked List의 유효성을 검사합니다. head와 tail 포인터가 null인 경우, next와 prev 포인터가 null인 경우 유효성을 검사하지 않습니다.
2025-05-13 10:02