当前位置:  首页>> 技术小册>> PHP合辑5-SPL标准库

双向链表是一种包含对下一个和上一个节点链接的链表。双向链表(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列表中存在的元素总数。

示例:

  1. <?php
  2. // Program to implement basic PHP functions
  3. // for doubly linked list
  4. // Instantiating an object of class SplDoublyLinkedList
  5. $dlist = new SplDoublyLinkedList();
  6. // Inserting elements at the end of the list
  7. $dlist->push('geeks');
  8. $dlist->push('for');
  9. $dlist->push('practice');
  10. // Displaying the list
  11. echo "Original List : ";
  12. for ($dlist->rewind(); $dlist->valid(); $dlist->next()) {
  13. echo $dlist->current()." ";
  14. }
  15. // Deleting element from the end of the list
  16. $dlist->pop();
  17. // Adding a new element at specific index
  18. // Add 'code' at index 2
  19. $dlist->add(2, "code");
  20. // Displaying the updated list
  21. echo "\n\nUpdated List : ";
  22. for ($dlist->rewind(); $dlist->valid(); $dlist->next()) {
  23. echo $dlist->current()." ";
  24. }
  25. // Printing the count of nodes
  26. echo "\n\nCount = " . $dlist->count() . "\n";
  27. // Printing the node at top of the list
  28. echo "Top = ". $dlist->top() . "\n";
  29. // Printing the node at bottom of the list
  30. echo "Bottom = " . $dlist->bottom() . "\n";
  31. ?>

output:

  1. Original List : geeks for practice
  2. Updated List: geeks for code
  3. Count = 3
  4. Top = code
  5. Bottom = geeks