How to implement stack data structure in Java without using collections.
Implementing Stack without using Collections
//
Create interface called Stack
public
interface
Stack {
void
push(Object value);
Object
pop();
int
length();
}
//
Create class implementing Stack interface named StackImpl
public
class
StackImpl implements
Stack {
private
Node head;
private
int
length;
@Override
public
void
push(Object value)
{
Node
node
= new
Node(value);
if
(head
== null)
{
head
= node;
}
else
{
node.next
= head;
head
= node;
}
length++;
}
@Override
public
Object pop() {
Object
result
= null;
if
(head
!= null)
{
result
= head.value;
head
= head.next;
length--;
}
return
result;
}
public
int
length() {
return
length;
}
private
class
Node {
private
Object value;
private
Node next;
public
Node(Object value)
{
super();
this.value
= value;
}
}
}
//
Test StackImpl
public
class
StackTest {
public
static
void
main(String args[])
{
Stack
stack
= new
StackImpl();
stack.push("stack
1");
stack.push("stack
2");
stack.push("stack
3");
stack.push("stack
4");
stack.push("stack
5");
stack.push("stack
6");
System.out.println(stack.pop()
+ "--"+stack.length());
System.out.println(stack.pop()
+ "--"+stack.length());
System.out.println(stack.pop()
+ "--"+stack.length());
}
}
Comments
Post a Comment