라이브러리
[PHP] SplDoublyLinkedList::add - 지정된 인덱스에 새 값을 추가/삽입합니다.
SplDoublyLinkedList
PHP의 `SplDoublyLinkedList` 클래스는 이중 연결 리스트를 구현한 클래스입니다. 이중 연결 리스트는 양방향으로 연결된 노드의 집합을 의미하며, 각 노드는 이전 노드와 다음 노드에 대한 참조를 가지고 있습니다.
SplDoublyLinkedList::add
`SplDoublyLinkedList::add` 메소드는 이중 연결 리스트의 끝에 새로운 노드를 추가합니다. 이 메소드는 두 개의 오버로드가 있습니다.
# 1. SplDoublyLinkedList::add($value)
이 오버로드는 새로운 노드에 지정된 값을 추가합니다.
#hostingforum.kr
php
$dll = new SplDoublyLinkedList();
$dll->add(1);
$dll->add(2);
$dll->add(3);
print_r($dll->toArray()); // 출력: Array ( [0] => 1 [1] => 2 [2] => 3 )
# 2. SplDoublyLinkedList::add($index, $value)
이 오버로드는 지정된 인덱스에 새로운 노드를 추가합니다. 인덱스는 0부터 시작합니다.
#hostingforum.kr
php
$dll = new SplDoublyLinkedList();
$dll->add(1);
$dll->add(2);
$dll->add(3);
$dll->add(1, 4); // 1번 인덱스에 4를 추가
print_r($dll->toArray()); // 출력: Array ( [0] => 1 [1] => 4 [2] => 2 [3] => 3 )
예제: 이중 연결 리스트의 사용
이중 연결 리스트는 여러 가지 상황에서 사용할 수 있습니다. 예를 들어, 큐나 스택을 구현할 때 사용할 수 있습니다.
#hostingforum.kr
php
class Queue {
private $dll;
public function __construct() {
$this->dll = new SplDoublyLinkedList();
}
public function enqueue($value) {
$this->dll->add($value);
}
public function dequeue() {
if (!$this->dll->isEmpty()) {
return $this->dll->shift();
} else {
throw new Exception('Queue is empty');
}
}
public function isEmpty() {
return $this->dll->isEmpty();
}
}
$queue = new Queue();
$queue->enqueue(1);
$queue->enqueue(2);
$queue->enqueue(3);
print_r($queue->dequeue()); // 출력: 1
print_r($queue->dequeue()); // 출력: 2
print_r($queue->dequeue()); // 출력: 3
이 예제에서는 이중 연결 리스트를 사용하여 큐를 구현했습니다. `enqueue` 메소드는 새로운 노드를 추가하고, `dequeue` 메소드는 노드를 삭제합니다. `isEmpty` 메소드는 큐가 비어있는지 여부를 확인합니다.
-
- 나우호스팅 @pcs8404
-
호스팅포럼 화이팅!
댓글목록
등록된 댓글이 없습니다.