Using PHP to describe some of the application examples of data structure stacks

Source: Internet
Author: User

Reprint: http://www.lamper.cn/html/2007/03-21/61.html

1, using PHP to describe the data conversion

The conversion of decimal N and other D-ary numbers is the basic problem of computing implementation, and there are many solutions, one of the simple algorithms is based on the following principles:
n= (N div d) *d+n mod D (where div is divisible operation, mod for remainder operations)
<?php
function convert ($num)
{
$stack = Array ();
while ($num) {
Array_push ($stack, $num%8);
$num = Floor ($num/8);
}
while ($stack) {
echo Array_pop ($stack);
}
}

?>

Test instance:
<?php
CONVERT (1348);
?>

2, brackets matching the test
Suppose an expression allows you to include two types of parentheses: parentheses and brackets, which are nested in a random order, that is, [] () or [()] as the correct format. But [(]) or [()] or (()] are not in the correct format.
The algorithm used in PHP to verify the validity of the expression bracket reference is as follows:
<?php
$str is an expression
function Check ($STR)
{
$stack = Array ();
$strLength = strlen ($STR);
for ($i =0; $i < $strLength; $i + +) {
Switch ($str [$i]) {
Case "(":
Array_push ($stack, $str [$i]);
Break
Case "[":
Array_push ($stack, $str [$i]);
Break
Case ")":
if (count ($stack) && array_pop ($stack) = = "(") break;
else return false;
Case "]":
if (count ($stack) && array_pop ($stack) = = "[") break;
else return false;
}
}
if (count ($stack) >0) return false;
else return true;
}

?>


Test instance:
<?php
$str = "LK (asdf) []";
Var_dump (check ($STR));
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.