05c02-1.php
来自「介绍PHP5的给类型函数应用」· PHP 代码 · 共 90 行
PHP
90 行
<?php// A library to implement stacks in PHP via arrays// The Initialize function creates a new stack:function &stack_initialize() { // In this case, just return a new array $new = array(); return $new;}// The destory function will get rid of a stackfunction stack_destroy(&$stack) { // Since PHP is nice to us, we can just use unset unset($stack);}// The push operation on a stack adds a new value unto the top of the stackfunction stack_push(&$stack, $value) { // We are just adding a value to the end of the array, so can use the // [] PHP Shortcut for this. It's faster than usin array_push $stack[] = $value;}// Pop removes the top value from the stack and returns it to youfunction stack_pop(&$stack) { // Just use array pop: return array_pop($stack);}// Peek returns a copy of the top value from the stack, leaving it in placefunction stack_peek(&$stack) { // Return a copy of the value on top of the stack (the end of the array) return $stack[count($stack)-1];}// Size returns the number of elements in the stackfunction stack_size(&$stack) { // Just using count will give the proper number: return count($stack);}// Swap takes the top two values of the stack and switches themfunction stack_swap(&$stack) { // Calculate the count: $n = count($stack); // Only do anything if count is greater than 1 if ($n > 1) { // Now save a copy of the second to last value $second = $stack[$n-2]; // Place the last value in second to last place: $stack[$n-2] = $stack[$n-1]; // And put the second to last, now in the last place: $stack[$n-1] = $second; }}// Dup takes the top value from the stack, duplicates it, // and adds it back onto the stackfunction stack_dup(&$stack) { // Actually rather simple, just reinsert the last value: $stack[] = $stack[count($stack)-1];}// Let's use these to create a small stack of data and manipulate it.// Start by adding a few numbers onto it, making it: 73 74 5$mystack =& stack_initialize();stack_push($mystack, 73);stack_push($mystack, 74);stack_push($mystack, 5);// Now duplicate the top, giving us: 73 74 5 5stack_dup($mystack);// Check the size now, it should be 4echo '<p>Stack size is: ', stack_size($mystack), '</p>';// Now pop the top, giving us: 5echo '<p>Popped off the value: ', stack_pop($mystack), '</p>';// Next swap the top two values, leaving us with: 73 5 74stack_swap($mystack);// Peek at the top element to ensure it is 74echo '<p>Current top element is: ', stack_peek($mystack), '</p>';// Now destroy it, we are done.stack_destroy($mystack);?>
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?