Queue is characterized by FIFO, like queuing in daily life. A queue includes operations such as adding a team's tail, deleting an element from the team's head, obtaining the team's tail element, obtaining the queue length, and determining whether the queue is empty.
The queue can also be implemented using a sequence table or a linked list, but it is best not to use a sequence table for the queue, because an operation to add or delete an element will always cause the movement of all elements, extremely low efficiency (except for cyclic queues ).
The implementation of the queue is very simple. The following describes how to implement a single-chain table.
Code : /*
* File: queue. CS
* Author: Zhenxing Zhou
* Date: 2008-12-07
* Blog: Http://www.xianfen.net/
*/
Namespace Xianfen. net. Datastructure
{
Public Class Queue < T >
{
Protected Singlelinkedlist < T > M_list;
Public bool isempty
{< br> Get { return m_list.isempty ;}
}
Public int count
{< br> Get { return m_list.count ;}
}
Public Queue ()
{< br> m_list = New singlelinkedlist T > ();
}
Public Queue (T)
{< br> m_list = New singlelinkedlist T > (t );
}
PublicT dequeue ()
{
T=M_list.gettail ();
M_list.removetail ();
ReturnT;
}
Public VoidEnqueue (T)
{
M_list.addhead (t );
}
PublicT getfront ()
{
ReturnM_list.gettail ();
}
PublicT getrear ()
{
ReturnM_list.gethead ();
}
}
}
2. Application Example
It is also a very boring demonstration. Program : Displays the parity pairs of randomly generated integers. Queue < Int > Q1 = New Queue < Int > ();
Queue < Int > Q2 = New Queue < Int > ();
Random RND = New Random ();
For(IntI= 0; I< 20; I++)
{
IntValue=RND. Next ();
If (value % 2 ! = 0 )
{< br> q1.enqueue (value );
}< br> else
{< br> q2.enqueue (value);
}< BR >}
While(!Q1.isempty&& !Q2.isempty)
{
Console. writeline ("Parity: {0 },{ 1}", Q1.dequeue (), q2.dequeue ());
}
Running result: parity pair: 1001667163,570500228
Parity: 703882551,1134267770
Parity: 1938115213,486438246
Parity: 1471693833,717831946
Parity: 429728181,678751398
Parity: 1894142101,2052360200
Parity: 1289719185, 1630602020