Stacks By Rugaia omer ahmed Stacks A stack
Stacks By Rugaia omer ahmed
Stacks • A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving data. • A stack is a container of objects that are inserted and removed according to the last-in-first-out (LIFO) principle. Objects can be inserted at any time, but only the last (the most-recently inserted) object can be removed. • Inserting an item is known as “pushing” onto the stack. “Popping” off the stack is synonymous with removing an item.
A stack is an abstract data type (ADT) • A stack is an abstract data type (ADT) that supports two main methods: • - push(o): Inserts object o onto top of stack Input: Object; Output: none • - pop(): Removes the top object of stack and returns it; if stack is empty an error occurs Input: none; Output: Object
An Example of Stack top top 9 Push(8) 7 2 top 7 2 pop() 8 8 Push(2) 9 9 7 7 2 2 top 9 7 2 pop() top 2 8 pop() 9 7 2
Stacks Methods • The following support methods should also be defined: • - clear()—Clear the stack. • is. Empty()—Check to see if the stack is empty. • push(el)—Put the element el on the top of the stack. • pop()—Take the topmost element from the stack. • top. El()—Return the topmost element in the stack without removing it.
Application • Real world application: – – Pile of plates Wearing or removing bangles. Reverse of a word Stack of books etc. • Technical application: – – Expression Evolution Expression Conversion (infix, pre-fix, post-fix) Parsing Simulation of recursion etc.
A Stack Interface in Java • While, the stack data structure is a “built-in” class of Java’s java. util package, it is possible, and sometimes preferable to define your own specific one.
Algorithm • STEP 1 START • STEP 2 Store the element to push into array • STEP 3 Check if top== (MAXSIZE-1) then stack is full else goto step 4 • STEP 4 Increment top as top = top+1 • STEP 5 Add element to the position stk[top]=num • STEP 6 STOP
- Slides: 8