双向链表是一种包含对下一个和上一个节点链接的链表。双向链表(DLL)包含一个额外的指针,通常被称为previous指针,和在单向链表中存在的next指针和数据。与单向链表只能单向遍历不同,双向链表允许双向遍历。
以下是理解双向链表概念的重要术语:
Link:链表中的每个节点可以存储一个被称为Link的指向另一个元素的指针。
Next:链表中的每个节点都包含一个被称为Next的指向下一个节点的链接。
Prev:链表中的每个节点都包含一个被称为Prev的指向上一个节点的链接。
SplDoublyLinkedList类是一个PHP库类,它提供了PHP中双向链表的主要功能。
以下是SplDoublyLinkedList类的一些基本函数:
push():此函数用于在双向链表的末尾插入一个新节点。
语法:
list_name.push(value);
这将在list_name列表的末尾推送值。
pop():此函数用于从双向链表的末尾删除一个节点。
语法:
list_name.pop()
这将从list_name列表中删除最后一个节点。
top():此函数用于选择双向链表的末尾节点。
语法:
list_name.top()
这将返回list_name列表中的最后一个节点。
bottom():此函数用于选择双向链表的开头节点。
语法:
list_name.bottom()
这将返回list_name列表开头的节点。
add():此函数用于在双向链表中指定的索引处插入新值,这也将导致该索引处之前的值(以及所有后续值)在整个列表中向上移动。
语法:
list_name.add(‘index’, “value”);
这将在list_name列表中的位置index添加值。
count():此函数用于计算给定双向链表中的元素数。
语法:
list.count()
这将返回list_name列表中存在的元素总数。
示例:
<?php
// Program to implement basic PHP functions
// for doubly linked list
// Instantiating an object of class SplDoublyLinkedList
$dlist = new SplDoublyLinkedList();
// Inserting elements at the end of the list
$dlist->push('geeks');
$dlist->push('for');
$dlist->push('practice');
// Displaying the list
echo "Original List : ";
for ($dlist->rewind(); $dlist->valid(); $dlist->next()) {
echo $dlist->current()." ";
}
// Deleting element from the end of the list
$dlist->pop();
// Adding a new element at specific index
// Add 'code' at index 2
$dlist->add(2, "code");
// Displaying the updated list
echo "\n\nUpdated List : ";
for ($dlist->rewind(); $dlist->valid(); $dlist->next()) {
echo $dlist->current()." ";
}
// Printing the count of nodes
echo "\n\nCount = " . $dlist->count() . "\n";
// Printing the node at top of the list
echo "Top = ". $dlist->top() . "\n";
// Printing the node at bottom of the list
echo "Bottom = " . $dlist->bottom() . "\n";
?>
output:
Original List : geeks for practice
Updated List: geeks for code
Count = 3
Top = code
Bottom = geeks