Queues and Stacks: Two stacks implement queues, two queues implement stacks

WBOY
Release: 2016-08-08 09:22:03
Original
962 people have browsed it

1. Question: Use two stacks to implement a queue. First use a stack to enter data, and then output this stack to another stack to form a first-in-first-out order for the queue.

Because PHP’s array can simulate the implementation of a stack, the code is as follows:

<?php
function StackToQueue($data)
{
	$arr=array();
	while($_t=array_pop($data)) 
	{
		array_push($arr, $_t);
	}
	return $arr;
}
$a=array();
for($i=1;$i<=5;$i++)
{
	array_push($a, $i);
}
var_dump($a);
$a=StackToQueue($a);
var_dump($a);
Copy after login
2, Use two queues to implement a stack. The order of the stack is mainly first in, last out. First use queue A to enter data, and then transfer the data from queue A to queue B every time the data is fetched. Only the last number is left in queue A, and then the data from queue A is dequeued to be the last element. Each time the queue data is transferred back and forth.

Copyright Statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.

The above introduces queues and stacks: two stacks implement queues, and two queues implement stacks, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template