1 <?php 2 #带哨兵的双链表实现 3 4 #链表节点 5 class Node { 6 public $pre = null; 7 public $next = null; 8 public $key = null; 9 } 10 11 #查找链表值 12 function search($list, $key) { 13 $cnode = $list->next; 14 while ($cnode !== $list && $cnode->key !== $key) { 15 $cnode = $cnode->next; 16 } 17 18 if ($cnode === $list) { 19 return false; 20 } else { 21 return $cnode; 22 } 23 } 24 25 #插入节点 26 function insert($list, $new_node) { 27 $list->next->pre = $new_node; 28 $new_node->next = $list->next; 29 $new_node->pre = $list; 30 $list->next = $new_node; 31 } 32 33 #删除链表节点 34 function delete($del_node) { 35 $del_node->next->pre = $del_node->pre; 36 $del_node->pre->next = $del_node->next; 37 unset($del_node); 38 } 39 40 #遍历链表 41 function traverse($list) { 42 $cnode = $list->next; 43 while ($cnode !== $list) { 44 echo $cnode->key . " "; 45 $cnode = $cnode->next; 46 } 47 echo "<br>"; 48 } 49 50 $list = new Node(); #list节点是个哨兵 51 $list->pre = $list; 52 $list->next = $list; 53 $head = new Node(); 54 $mid = new Node(); 55 $tail = new Node(); 56 $head->key = 0; 57 $mid->key = 1; 58 $tail->key = 2; 59 $list->pre = $tail; 60 $list->next = $head; 61 $head->pre = $list; 62 $head->next = $mid; 63 $mid->pre = $head; 64 $mid->next = $tail; 65 $tail->pre = $mid; 66 $tail->next = $list; 67 traverse($list); 68 $insert = new Node(); 69 $insert->key = 3; 70 insert($list, $insert); 71 traverse($list); 72 delete($insert); 73 traverse($list); 74 print_r(search($list, 1)->key); 75 ?>
0 1 2
3 0 1 2
0 1 2
1