0% found this document useful (0 votes)
53 views27 pages

Problems DSA - Stack & Queue

The document outlines various Java programming tasks involving data structures such as queues and stacks. It includes algorithms for manipulating these structures based on specific conditions, such as calculating digit sums and prime factors. Each task is described with examples and expected outcomes for clarity.

Uploaded by

datascience9029
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views27 pages

Problems DSA - Stack & Queue

The document outlines various Java programming tasks involving data structures such as queues and stacks. It includes algorithms for manipulating these structures based on specific conditions, such as calculating digit sums and prime factors. Each task is described with examples and expected outcomes for clarity.

Uploaded by

datascience9029
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

J.

Priority~ fOt" E~loyft '-1-c


Wratt a ~ ~ • tNt .ccrpu • IIOl·npty iA\r~ (Stri11 ~ ) with uc• dnst I• tllt fcrut
",-1,or.P'- •:rri". "lit P"oC"• d·oold
rtturn • o.-t\trO.ww (froat ·, k¥) ti.~ er, tilt follc:wtac lcclc:
Arr-c, ""lc,;«s lii U<tndillC ordtr of r,r.l;.
If tw flll)lo,tn hM> It~ ~ rri, vranct thn lrJICO("a,hiull, t., m,1-r'.aw.
"4 ,11 ,lewstt to eut\i,<ww l11 !~ IOrttd ordrr.
lttUl"II au~! r<lww .

Er111Plt.
l n \ t ~ • ("Jctll J", '4litr 1•, -~ 1•, 0
Ev, l'J
out\t~ • [ Evt J', '411c, l°, 'loll l',
0 0
Joflll ) 0 )
public cl~ss Prob lcmNo l (

puhl i c 8t.--.t :Io v o 1d m.a i n ( S t r:: i nq () ur.go ) f

Oucue2 queue tH? w Oue u e2 ( 7 ) ;


qu ue.enqueue ( "' hn
qu u .enqueue ( ..
qu u . nquoue("
.cnqueuo("
. nu u (4);

Ou ue2 u· putOu u c: e znpl oy eARank (gucn.1n ) :I


I
n n("Ev nly h .v1 1 l nurnc1:2t• ,.
u . displa y () :
I

public stati c Queue2 emp l o yeeRank( Oueue2 qu e ue ) (


Oueue2 o u t Q = ne w Oueue2(q ue ue . getMa xSize()) ;
Oueue2 ql = new Queue2(que ue . getMa xsize( ));
Oueue2 q2 = new Oueue2 (que ue . getMa x Size ());
Queue2 q3 = new Oueue2 (gueue . getMa xS i ze ());
while ( l queue . isEmpt y ()) (
String str = queue . dequeue ();
i f( st. r . charAt.( str . l ength() -1 ) == • ' ) (
ql . e ngueue( str ) ;
)
else if( st r . charAt( str . length()- 1 ~= ' ' ) (
q _ . enqueue( st:r ) ;
)
else i f ( t:r . c harAt.( 1:r . l e ng t.h() - l ) == ' ' ) (
. . enqueue ( -r ) ;
whi le ( ! q l . i sEmpt y () )
(
outO . enqueue( ql .dequeue()) ;
}
while ( !q2 . isEmpty ()) {
o utO . enqueue( q2 . degueue()) ;
)
whj 1e ( ! q3 . isEmpty (} ) (
o utQ.enqueue( q3 . dequeue()) ;
}
return utO;
}
)
2: Stack Nusber Manipulation Based on Digit Sun
Write a Jva program that accepts anon-enpty intntStack (Botton Top) as input and returns
logic: an out IntStack (Top-> Botton) based on the folloing
For each elenent in inIntStack, calcolate the sun of its digits.
1f the digit sum is odd, add the elenent to tenpDataStructurel.
1f the digit sun is even, add the elenent to
After processing all elenents:
tenplataStructure2.
Push all elesents fron tencOataStructurel to out TntStack in
Then push all elerents from reverse order.
Return outIntStack, tenpatastructure2 in the sare order as they appeared in intntstack.,

Exanple:
inintStack [34, 56, 12, 29, 81]
outIntStack (81, 29, 12, 56, 34]
queue.onqueue (81)
queue.enqueue (29)
queue.enqueue (12)
queue.enqueue (56)
queue.enquoue (34)
splitQueue (queue):
public static Queue splitQueue (Queue queue) |
Queue Odd nev Queue (queue.qetMaxSize () ):
Queue even = new Queue (queue.getMaxslze () )
Queue outqueue = new Queue (queue.get.MaxSize()):
int n:
int r
int sum-0:
swhile (! queue.inEnpty ())I
int a queue.dequeue ():
n- at10;
r - a/10:
um=n +ri
if (sunt2--0)
even.enqueue (a)
clse
Odd.enqueue (a)
wbile (!0dd. iaEmpty())
outqueue.enqueue (odd.de_ueue ()):
(!even.isErpty ())
whileoutqueue.enqueue (
(even.dequeue ()):

outqueue.display ()
return outqueue
) : ~uc P1lrlnc tilth Le1lc0&riplllc,l Onkr for Stri~t 0
Wrltf • J•v• Pl'O&rll thtl l((tpU • llOll•f~ly lnStl'()Jtutl and lnSt~1 (Strine ~tUH), uch contelnlnc ,trlnc, forNtttd Ill "produ,t : c1ll'f01'V •

1hr rrocru 1h~uld r,turn 11ut\tr01,llt' (rront •> Rur) ~Htd on tht fol1CJ11ln& Ioele:

ror mh corrupondln1 rlrefllt froa lnSt~I --, lnSt~d:


(011J1r1 prod~ct lulc111r1phlc,lly.
II product froe lnSl~tutl cow& btfort product froa ln5t~utJ, ccnutt11Jtr the h<I tl~nh with • · " end edd lt lo t,-0.h'itruclurr.
H pro,!11c1 fl'OII lnSt~MJ cost1 hefOt't, rtWrtf tht concott11Jtl011 ol'dtr.
Add 11,r rlrnnh rroa 1~11\tnKtur, to 01i1St~, In tht lllf ordtr .
Rrturn 01JISlrQutu,.

harp It :
lnSt~rutl • ["L1plC1):Elt<trcnlc1•, "Al!Olr:Frult", •~htq,oo:Tnllrtrv"J
!nSlr~out1 • ("111!1,1 :El.rtronln", •tinen~ :Jrutt• , "So,J,:Tolltlrv")
ou1Str()um • I "LAplop• Tabltt •, "Ac,plt •e.n&u•, "Shapoo·SoAJ>" I
cue ql = new Oucue(J);
ql.enqueue( L~ pt op " );
0

ql. enqueue ( ••;-_~':' 1 .. ,. ) ;


ql. enqueue ( .. :.Hl~:. ;-'u,., " ) ;
Queue q 2 = new Oueue(3);
q~.enqueue( " 7abl e ' );
q2. enqueue ( ... :3an.ar~a " ) ;
q 2 . enqueue ( S..:L!~ " ) ;
H

Queue ou t Q~eue = lex o graphic( q l,q2 );


outc-~eue .display();
)

pub1ic static Queue lexo graphic(Oueue ql , Queue q2 ) {


Queue c~ ~O~eue = new Oueue( ql .getMaxSize());
while ( ! ql . is£.-npty () I I ! q:! .isEmpty () ) {
String s~ r l = ql .dequeue();
S~ring s~=~ = q~ .dequeue();
if( s~=: .charAt( O) >s~r! .charAt(O)) (
,, , , ~
.- •• !:""-.;;.-
.J - - - •• • • ·-- ....
-' ........... ~---- ., """', ,,.,_i.- -~ " >.
- • r · .. ~ ._.. I
-- ~ - .
J. • .. '- • .. ,

- .. -,-. .. "' .. enquQuc::.( - t -1 ) ·


~
J
--- -- --- -
else

, I
I
4: Stack Manipulation Based on Prine Factor Count
Meite a Java progran that accepts a non-empty intntStack (Botton -> Top) as an input parameter and returns an outTntStack (Top > Bottom)
the following logic: based on

For each elesent in inIntStack, calculate the nunber of prine factors.


1f the nunber of prine factors is odd, add the elesent to tenpataStructurel.
If the nunber of prine factors is even, add the elenent to tespOataStructure2.
Push all elenents from tespõatastructurel to outIntStack in the sane
Then, push all elesents fron order as they appear in intntStack.
tempDataStructure2 to outIntStack in reverse order.
Return out IntStack.

Exanple:
intntStack (12, 15, 9, 12, 21)
outIntStack (15,9,21, 12, 12
public static Stack stackMulPrime Factor (Stack stack) (
Stack outStack = new Stack (stack.getMaxsize ()) :
Stack evn = new Stack (stack.getMaxSize () ):
Stack tempEvn = new Stack (stack. getMaxSize (0)
Stack odd = new Stack (stack. getMaxSize ())
while (!stack.isEmpty ()) {
int num = stack.pop () i
if (noOf PrimeFactor (num) % 2 = 0)(
tempEvn.push (num) :
else {
odd.push (nm) ;

while (!tempEvn.isEmpty () )
evn.push (tempEvn.pop () ) :
while (!odd.isEmpty ())
outstack.push (odd.pop () )
while(!evn.isEmpty ()) {
Outstack.push (evn.pop()):
Ieturn outStacki
5: Prine Pair Sun Using Tho Queues
rite a Jeva progran that accepts tio non-enpty queves, inlntQuevel and intntQueue2 (Front -> lear), and returas outIntQueue (Front > Rear) based
on the follaing logiet

For each elenent in intntQuevel, check if there exists an elerent in inntQueue? such that the sun of the to elesents is a prine nunber.
If the sun is prine, ad4 the to elenents as a pair (elementFronQuevel, elementFromQueve2) to tesDataStructure.
After processing, add all pairs in tepataStructure to outIntQueue in the sane onder.
Return outIntueue,

Exanple:
inTntQueuel (2, 7, 5]
inintQueue2 (11, 4, )
outIntQueue (2, 1, 7, 4,5,9)
pusliC Class Q5 PrETHftors.
public static void main (Stríng|] args) |
Queue inqueuel new Queue (10) :
inqueuel.enqueue (2)
T inqueuel.enqueue (7)
inquouel.enqueue
Queue
(5)
1nqueue2- nev Queue (10)
inqueue2.enqueue (11) :
inqueue2.enqueue (4)
inqueue2.enqueuc (7):
PrimeQucue (inqueuel, inqueue2)
public statíc Qaeue PrineQueue (Queue inqueuel, Queue inqueue2)
int 4,bi
Queue out
int sun
nev Queuc (inqueue 1l.qetHaxSize() )!
while (! inqueuel.iaEmpty(0 nqueue2. Iafnpty() )
a-inqueuel.dequeue ()
binqueue2.dequeue ()
int flag-0:
aum-a +b:
for (int i-lzic-gun it+)
if (sum i--0) (
flag++:

out.enqueue (a):
out.cnqueue(b)

out.display ()1
return outi
6· ~ar• ,rJ l ut,,. Kot,h 1n ~ t •nd S:1d
Wrl!r • ,,.., P'oC'• !hit 1ccrph • I\Jl\·flll)ty 1-rnt\Ud (lo:tcr. ·> lop) end lnlnt~t (frcnt •> Rur), rttlll'tllnc.,, ou!lnt~ni• (front ·> ••,r)

fc• tJ<h rl-nt • 1n tnlnt~t,<k, cht,, if tl>frt nhh ,n tl'9tflt y in inlnt~ wch that 1"2 , y"3.
If • Nt1h1rc p,u, n f"'1tld, dJ • ,nd y to tna').)t,Strvct~ in tht ordtr (1, y) .
.Ud ,II i,41r1 ln ttwl>'.l,t,Stnictu~ to outlnt(ww In tht - O"dfr tlwy wrt found.
Rrturn tu:lnt(u,,w.

£u1')lt
lnlnt~t,ck • 14, I, 9)
lnlntl\J""' • [1, l, 16)
outln!~ • [I CJ
publ.io c .l ass Pro blem6 (
public st~tic v oid main(String[ J args) (
Stack i n S tack = n e w Stack(3);
Queue inOueue = n e w Oueue(J);
inst:a c k . push(4) ;
inSt:ack . p u sh( S );
in S t:-a c k .push(9);

in~~euE .enqueue(2);
ir.~JEUE . enqueue( 4 );
in~~E u ~ .encr.1eue( l t);

Queue r: u c -:tJ E:.l"? = sqrCubNacch ( in S t:a c ic , in0·.1EU'E' );


c·J::':i;;,u,e; . display ();
I
puhl i c st.cl ti c Ou9ue sqrCubMat:ch (Stack inSt.a c .ic , Queu e inc.•·.1eu..- ) t
C,-u~u~ -: .. ~ :-'-..:-,, • now Queue Ci r.~:.t 'l:'U -? . getMaxSi ::e () ) ;
=• ()
(, _ _ . .--: - · :· - • = r.~•. ." : .J"='~-~ 1 1.r-. _ .1 -;- t .. • ·. 1 ··~C! "' ='! a :..
1 >;
vWlu C! ::.s :.,. ,:; ,: . i s ~ t y () && I ;.n ,;. ua;; u 'l' . is£mpt i• ()) (
int x =:.1.z · ,,: r. . p,:,p() 1
int: :,· = : : . :. .-- ·"" - d,;,~ueuo!" C) ;
1 t · ff'..--:.n.s: :-i ·c z , ~ >== ~ath - F..:>1,• f ~· , 3) >
: ; !. : ;-· , .. • "in =1..1 .. 1.oai ( .-: ) ,
. .. ": :, ,..,_ .,:. • •n -=IU'WUtif f i ' ) I
f
public static Queue compare(Stack inStack,Queue inQueue) (
Queue Q = new Queue(inStack.getMaxSize());
while ( l ins tack. isE.mpty ()) (
Strings= inStack.pop();
String name= inQueue .dequeue();
int num = Integer.parseint(inQue ue.dequeue());
i f ( s . equals ( " " +na:ne . charAt ( num) ) ) (
Q.enqueue( s );
)
I
else {
Q.enqueue( "-1 " );
)
)

return Q;
)
l
10: Write a Java program that sccepts to non-empty queves, inlatQueuel and inlntQueue2, each containing integers. The progrun should return
outIntQueue (Front -> Rear) based on the folloing logic:
For each corresponding pair of elesents from inlntQuevel and inlatQuee2 (Front -> Rear):
1f the eleent fron inlntQueuet is even, calculate the sum of the pair and add it to tendatastructure.
If the elenent fros inlntQueuel is odd, calculate the difference (inlntQuevel eleent inlntQueue2 elenent) and add it to tenpDataStruc ture.
1f any elesents resain in either inIntQueuel or inlntQueue2 after pairing, add thes directly to outIntQueue in the sose order as they appear.
Finally, add all elesents fron torgbatastructure to outintQueue in the sane order,
Return outIatQurue.

Exonple:
inintQueuei [2, 7, 4, 9]
inintQueve? (3, 6, 5, 2, 10)
outIntQueue (5, 1, 9, 7, 10)
UPrcesidanceP.
publia static Queue findouto (0ueue Problerm7,jva
Oueue outo new ueue inQ1, Queue in92) (
int index = 0; (inQl.getMaxSize +inQ2.getMaxSize ()
() )
1f
(inQ1.getMaxSize (0<=
in02.getMaxSize())
index= inQl.getMaxSize (): (

else (
index= in02.getMaxSize () :
for (int i = 0; i < index; it+)
int nl = inQ1. dequeue ()
int n2 = inO2. dequeue ()
int result= 0;
if (nl2 == 0) (
result = nl + n2

else (
result = n1 - n2;

outQ.enqueue (result) ;
while (linQl.isEmpty 0) ( I
outQ.enqueue (inQl.dequeue ()):
whíle ( !in02.isEmpty ()) (
outQ.enqueue (ing2.dequeue ()):
return outCi
11 IMtt 1 , ••• proarn lNt tc<fPh I non ewpty lnStrSttck (St•~ St1<k) H III IIIOVt pt<Mtter and rtturn1 outS t~ (Strine ~tut) (front · >
R11r) bntd on tht follO!ii"I l011<

Each 111cUlt11!11t In tMtrSt,i• follM thh forut 'nploy ttllat dfp1rta


tntlio"
For uch 1t1<k[lfWMt
Chtck ii tllt n,lo n-• 1t.rh ,dth I VOIIII (A, i, I, 0, Ul.
II It d:>11, Md It to tl"lp0,11\tru<turtl.
OtheNht, ~ It to t"'°'tl\ t1'9<t ur,J.
Add 111 tltw11h of tllCOltl\tructurtl to wt\\~ tut la tht • • crltr
o thty -.,1rtc1 In lnStr\t11k.
Ihm edd di tltafll h of tnci0,ltt\trv<lurt2 lo outSt ~tut In tlw wt
ordtr.
lttur11 outSl~ fllt.

h-,1, ·
IIIStrStttk • l'All<t:Dl', 'lc:ill.OJ', 'ht:O l', 'Ou■r:Dl', "Charllt:DJ')
outS t~ • [01<ar:Dl ht:Dl Allct:Dl Charllr:D2 ilob:DJ
publ ic alas ■ Probl emll c
publ ic stati c void main (Strin g[] args) c
Stack inSta ck = nov Stack (S);
insta ck.pu sh ( "l.l 1c[}l " );
inSta ck .push ( '' Ro b02 " );
inSta ck.pu sh ( '' ~voUl '' );
inSta c k.pus h( ''O~cJ rDl " ) ;
insta c k.pus h( " Chi.1 r l 1n: .. );

Queue o u tO = c h e c.t :;ca c tW1 chV:> v a l ( i r.S :.a c k );


o utO,d ispla y() :I I
)
(
publ io sl,at.i c Queue check !>ta r t W1thVo vel (Stac k 1n !; ta c lc )
Oueue c utQ = now o~ ~ue( 1n : : 1c k . getMaxs1. :e()) ;
Queue t~:npl - now Oueue ( 1n.C- t.1 c -= . get MaxSi .:e()) ;
Queue tE:np.:! = nuw Ou -=-ue ( 1 ,.~ :.ac k . qe t~.ax s .1::e () ) ;
St rin g st r = ... ~IO U .. ;
vh ilo (li nS tac k.i sE mp ty ()) (
St rin gs = inS tac k.p op ();
if( str .c on ta in s( " " +s .ch arA t(0 )))
(
tem pl. en qu eu e(s );
)
el se (
tem p2 .en qu eu e(s );
)
)
wh ile ( I ter np l . is£ mp ty ()) (
o utQ .en qu eu e( tem pl .de qu eu e ()) ; I
)
wh ile (lt emp2 .is £m pty ()) (
o utQ .en qu eu e(t em p2 .de qu eu e() );
)
r e t ur n o ut O;
)
)
12: Write a Java progran that accepts a non-espty stack instrStack (Top -> Botton) and returns an
the folloving logic: output queue outStrQueue (Front -> Rear) based on

Input: The stack instrstack contains strings in the forsat Ites-Category> here:
Cotegory is either A, B, or C.
Category A: Represents high-priority itms.
Category B; Represents nediua-priority itees.
Category C: Represents lo-priority iteas.
Processing Logic:
For each elenent in Instrstack (Top -> Botton):
If the category is A, ove the elesent to tepDataStructurel (High-Priority List).
1f the category is B, ove the elesent to tenpoataStructure2 (hediu-Priority List).
1f the category is C, ove the elesent to tengDataStructure)
Final Queue Creation: Priority List).

First, add all elesests fros


Then, add.all elesents fron tenpDataStructurel (High-Priority) to outstrQueue in the order they appeared in
instrStack.
Finally, add all eleents frontenpDataStructure2
tepataStructures
(Nedius-Priority) to outstrQueut,
Return the outstrQueue hich contains the elesents (Low-Priority) to outStrQueut.
sorted by their priority (fros high to low).
instrsteck ('Laptop-A, "hair-", Book-C", Phone-A, "Table-8"]
outstrQueue ['Phone-A', "Laptop-A, "Chair-8", "Table-", "Book-(")
pubiiC class Problem12
public statie void main (String|] args)
Stack stack= new stack (5):
stack. push ("Laptop-A") :
stack.push ("Chair-B"):
stack.push ("Book-C"):
stack.push ("Phone-A") ;
stack.push ("Table-");
Stack outStack = orderedCatagaryWise (stack) ;
outStack. display () :
public static Stack orderedCatagaryWise (Stack stack) (
Stack outStack = new Stack
(stack.getMaxSize () ):
Stack CÃ = new Stack (stadk.getMaxSize () ):
Stack cB = new Stack (stack.getMaxSize () ):
Stacik cC = new Stack (stack.qetMaxSize ())i
while (!stack.isEmpty() ) getMaxSize(0);
(
String str =stack.pop ();
if(str.charAt (str.length (0-1) =='A')
CA.push (str):
else if (str.charAt (str.length () -1)
==*B)
CB.push (str)
else if (str.charAt
cC.push (str) i
(str.length () -1) ==*c')

while(!cC. isEmpty () )
String str = cC.pop ()
outStack. push (str)
whi le(1 cB. isEmpty () ) (
String str = CB.pop () :
outstack.push (str) :
while (! cA. isEmpty () )
String str = C£.pop() :
outstack.push (str);
return outStack;
inIntStack- 9,23,54
inIntQueue- 54,5,4,6
outIntQueue-549,235,544,6
public static void main(String[] args) {
Stack inIntStack =new Stack(10);
Queue inIntQueue = new Queue(10);
Queue outIntQueue = new Queue(10);

inIntStack.push(6);
inIntStack.push(21);
inIntStack.push(9);
inIntStack.push(18);
inIntStack.push(3);
inIntQueue.enqueue(19);
inIntQueue.enqueue(10);
inIntQueue.enqueue(33);
inIntQueue.enqueue(12);
inIntQueue.enqueue(14);
inIntQueue.enqueue(27);

while(!inIntQueue.isEmpty()&&!inIntStack.isEmpty()) {
int q=inIntQueue.dequeue();
int s=inIntStack.pop();
String r1=Integer.toString(q)+Integer.toString(s);
String r2=Integer.toString(s)+Integer.toString(q);

if(q>s) {
outIntQueue.enqueue(Integer.parseInt(r1));
}
else if(s>q) {
outIntQueue.enqueue(Integer.parseInt(r2));
}
}
while(!inIntQueue.isEmpty()) {
int q1=inIntQueue.dequeue();
outIntQueue.enqueue(q1);
}
while(!inIntStack.isEmpty()){
int s1=inIntStack.pop();
outIntQueue.enqueue(s1);
}
outIntQueue.display();
}

--------------------------------------------------------------------------------------------
-----------------------------------
inIntStack- 60,50,40,30,20,10
inIntQueue- 1,2,3
outIntQueue-1,60,50,40,2,30,20,10,3

public static void main(String[] args) {


Stack inIntStack =new Stack(10);
Queue inIntQueue = new Queue(10);
Queue outIntQueue = new Queue(10);

inIntStack.push(10);
inIntStack.push(20);
inIntStack.push(30);
inIntStack.push(40);
inIntStack.push(50);
inIntStack.push(60);
inIntQueue.enqueue(1);
inIntQueue.enqueue(2);
inIntQueue.enqueue(3);

int size=0;
Queue q = new Queue(10);
while(!inIntStack.isEmpty()) {
size++;
q.enqueue(inIntStack.pop());
}
int halfSize=size/2;

while(!inIntQueue.isEmpty()) {
outIntQueue.enqueue(inIntQueue.dequeue());
for(int i=0;i<halfSize;i++) {
outIntQueue.enqueue(q.dequeue());
}
outIntQueue.enqueue(inIntQueue.dequeue());
for(int i=0;i<halfSize;i++) {
outIntQueue.enqueue(q.dequeue());
}
outIntQueue.enqueue(inIntQueue.dequeue());
}
outIntQueue.display();

}
============================================================================================
===============

inStrStack- "Pantry-C1","Phone-F1","Clothing-F2","Book-C1","Decoration-F2"
outStrQueue- "Pantry-C1","Book-C1", "Phone-F1", "Clothing-F2","Decoration-F2"

public static void main(String[] args) {


Stack inStrStack =new Stack(10);
Queue cQueue = new Queue(10);
Queue fQueue = new Queue(10);
Queue outStrQueue = new Queue(10);

inStrStack.push("Decoration-F2");
inStrStack.push("Book-C1");
inStrStack.push("Clothing-F2");
inStrStack.push("Phone-F1");
inStrStack.push("Pantry-C1");
int cCount=0;
int fCount=0;

while(!inStrStack.isEmpty()) {
String s=inStrStack.pop();
for(int i=0;i<s.length();i++) {
if(s.charAt(i)=='-') {
if(s.charAt(i+1)=='C') {
cCount++;
cQueue.enqueue(s);
break;
}
else if(s.charAt(i+1)=='F') {
fCount++;
fQueue.enqueue(s);
break;
}
}
}
}

for(int i=0;i<cCount;i++) {
String a=cQueue.dequeue();
if(a.charAt(a.length()-1)=='1') {
outStrQueue.enqueue(a);
}
else if(a.charAt(a.length()-1)=='2') {
cQueue.enqueue(a);
}
}

while(!cQueue.isEmpty()) {
outStrQueue.enqueue(cQueue.dequeue());
}
for(int i=0;i<fCount;i++) {
String a=fQueue.dequeue();
if(a.charAt(a.length()-1)=='1') {
outStrQueue.enqueue(a);
}
else if(a.charAt(a.length()-1)=='2') {
fQueue.enqueue(a);
}
}

while(!fQueue.isEmpty()) {
outStrQueue.enqueue(fQueue.dequeue());
}

outStrQueue.display();

You might also like