java - Implementing Queues Using Linked Lists -
i'm trying understand how add method works listqueue revision. appreciated. unable find full explanations online , unfortunately can't head around it.
private cell frontcell,backcell; @override public void add(char x) { cell newcell = new cell(x); if(frontcell == null){ frontcell = backcell = newcell; }else{ backcell.next = newcell; backcell = newcell; } }
there inner class "cell"
public class cell{ char data; cell next; public cell(char data){ this.data = data; next = null; } }
"frontcell" stores cell @ beginning of queue , "backcell" stores cell @ back.
"frontcell" references "backcell" contains data got added. if character added "backcell.next = newcell" , "backcell = newcell".
how cells in-between front , cells in queue stored?
how referencing work "frontcell" being set "backcell"?
i not expert try explain way understand it.
when create queue empty, means front cell , cell, both null.
then when add new cell (cell 1)
cell newcell = new cell(x)
the new cell stores value x
, next cell null because haven't inserted between front , back, enters if because said frontcell null
if(frontcell == null){ frontcell = backcell = newcell; }
here new cell both front , , next cell null because there no other items.
when add cell (cell 2) time if code not triggered because front not null anymore code executed
backcell.next = newcell; backcell = newcell;
here last cell (the 1 have) changes next cell wich null point @ second cell , reference cell @ change first second one. if debug code @ point have like
firstcell= cell1 cell1.next= cell2 cell2.next = null = cell2
and if add cell have
firstcell= cell1 cell1.next= cell2 cell2.next = cell3 cell3.next=null = cell3
i hope helps undertand better
Comments
Post a Comment