Java Reference
In-Depth Information
Program 8.17
Minimal list implementation
class
List
int
element ;
List next ;
// Constructor
List(
int
el , List
tail )
this
.element=el;
this
.next=tail;
}
List insertHead(
int
el)
return new
List(el ,
this
);
}
}
Let us now use this linked list data-structure for supporting the methods
provided by the stack:
Program 8.18
Implementing the stack interface using a linked list as its
backbone data-structure
class
Stack
{
List
list ;
Stack ()
list=
null
;
}
void
Push(
int
el)
if
(list!=
null
)
list=list . insertHead( el ) ;
else
list=
new
List(el ,
null
);
}
int
Pull ()
{
int
val ;
if
(list!=
null
)
{
val=list . element ;
list=list .next;
}
else
val=
−
1;
return
val ;
}
}
Search WWH ::
Custom Search