Data Structures & Algorithms CHAPTER 6 Stacks Ms. Manal Al-Asmari
Stacks and Queues Define two new abstract data types *Both are restricted lists *Can be implemented using arrays or linked lists Stacks “Last In First Out” (LIFO) The last element inserted will be the first to be retrieved Queues “First In First Out” (FIFO) Ms. Manal Al-Asmari
Stack Overview Stack ADT Basic operations of stack *Pushing, popping etc. Implementations of stacks using *array *linked list Ms. Manal Al-Asmari
Stack ADT A stack is a list of the same kind of elements with the restriction that insertions and deletions can only be performed at the top of the list. The other end is called bottom Ms. Manal Al-Asmari
The Stack ADT Stack applications can be classified into four broad categories: reversing data, pairing data, postponing data usage backtracking steps Ms. Manal Al-Asmari
Conceptual Stacks Ms. Manal Al-Asmari
Stacks Stacks are also called Last Input First Output (LIFO) data structures. Operations performed on stacks: Push: Equivalent to insert Pop: Deletes the most recently inserted element Peek: Examines the most recently inserted element Ms. Manal Al-Asmari
Stack Operations Ms. Manal Al-Asmari
Push and Pop Primary operations: Push and Pop Push Add an element to the top of the stack B. Pop Remove the element at the top of the stack Ms. Manal Al-Asmari
Stacks implementation Any list implementation can be used to implement a stack Arrays (static: the size of stack is given initially) Linked lists (dynamic: never become full) Ms. Manal Al-Asmari
Implementation of Stacks as Arrays The array implementing a stack is an array of reference variables Each element of the stack can be assigned to an array slot The top of the stack is the index of the last element added to the stack To keep track of the top position, declare a variable called stackTop Ms. Manal Al-Asmari
Implementation of Stacks as Arrays Ms. Manal Al-Asmari
Constructors Default constructor Ms. Manal Al-Asmari
Initialize Stack Method initializeStack: Ms. Manal Al-Asmari
Empty Stack Method isEmptyStack: Ms. Manal Al-Asmari
Full Stack Method isFullStack: Ms. Manal Al-Asmari
Push Method push: Ms. Manal Al-Asmari
Peek Method peek: Ms. Manal Al-Asmari
Pop Method pop: Ms. Manal Al-Asmari
THE END Ms. Manal Al-Asmari