Stack
This chapter shows how to implement the most common operations on stack.
Chapter 3:
AlBaha University Faculty of Computer Science and Information Technology Course: Data Structures and Algorithms 1.2
Definition of stack
• Stack is a linear data structure which follows a particular order in
which the operations are performed.
• The order may be LIFO(Last In First Out) or FILO(First In Last Out).
AlBaha University Faculty of Computer Science and Information Technology Course: Data Structures and Algorithms 1.4
Definition of stack
• stack: A collection based on the principle of adding elements and
retrieving them in the opposite order.
• Last-In, First-Out ("LIFO")
• Elements are stored in order of insertion.
• We do not think of them as having indexes.
• Client can only add/remove/examine push pop, Top
the last element added (the "top").
top third element added to
second element added
bottom first element added
stack
Implementation
There are two ways to implement a stack:
• Using array
• Using linked list
AlBaha University Faculty of Computer Science and Information Technology Course: Data Structures and Algorithms 1.7
Implementing Stack using Arrays
class stackArMain
The elements pushed are
{ 1
public static void main(String arg[]) 9
2
{ 10
stackAr s = new stackAr(20);
stackAr R = new stackAr(50);
The elements printed are
s.push(1); s.push(9); s.push(2); s.push(10); 10
2
while(!s.isEmpty())
9
{ System.out.println(s.Top()); s.pop(); } 1
} // End of the main function
} // End ofUniversity
AlBaha the classFaculty
stackArMain
of Computer Science and Information Technology Course: Data Structures and Algorithms 1.12