Stack
Stack is the subclass of Vector and implements Serializable, Clonable, Collection and List interface. Stack is the representation of LIFO data structure in Java.
- Underlined data structure is Stack (LIFO).
- Heterogeneous data elements are allowed.
- Null insertion is allowed.
- Duplicates are allowed.
- Insertion order is preserved.
Constructor
Stack s=new Stack() //Creates an empty Stack
Methods
push(Object obj)
|
Insert an element on top of Stack
|
pop()
|
Remove and return an element from the top
of Stack.
|
peek()
|
Return an element from the top of Stack.
|
search(Object o)
|
Return the offset if the passed object is
found in Stack, -1 otherwise.
|
Example:
import java.util.*;
class StackDemo
{
public static void main(String[] args)
{
Stack s=new Stack();
for(int i=1;i<=5;i++)
{
s.push(i);
}
System.out.println(s.peek()); //Returns the element at the top of stack
System.out.println(s.pop()); //Remove and returns the element from top of Stack
System.out.println(s.search(3));
System.out.println(s.search(10));
}
}
class StackDemo
{
public static void main(String[] args)
{
Stack s=new Stack();
for(int i=1;i<=5;i++)
{
s.push(i);
}
System.out.println(s.peek()); //Returns the element at the top of stack
System.out.println(s.pop()); //Remove and returns the element from top of Stack
System.out.println(s.search(3));
System.out.println(s.search(10));
}
}
No comments:
Post a Comment