Stack Data Structure Chapter: Push, Pop, Peek Operations
1. DATA STRUCTURE
Chapter 6: Stack
Prepared & Presented by
Mr. Mahmoud R. Alfarra
2011-2012
College of Science & Technology
Dep. Of Computer Science & IT
BCs of Information Technology
http://mfarra.cst.ps
2. Out Line
What is Stack data structure?
Push operation
Pop operation
Retrieve the data of an element
Clear the Stack
Print all data of stack
Search about data
Stack Collection
2
3. What is the Stack?
Stack is a dynamic linear data structure.
Data in a stack are added and removed from
only one end of the list.
3
4. What is the Stack?
4
البيانات تراكيب مساق
إعداد العلمية المادة
/
أ
.
ا َّالفــر رفيق محمود
We define a stack as a list of items that are
accessible only from the end of the list, which
is called the top of the stack.
Elements are always removed from the top,
and inserted on the top also.
A stack is known as a Last-in, First-out (LIFO)
data structure
11. Pop operation
11
1. public void Pop()
2. {
3. if (Top == null)
4. Console.WriteLine("Stack is Empty!!");
5. else
6. {
7. Top = Top.next;
8. length--;
9. Console.WriteLine("Now Top Points to: " +
Top.name);
10. }
11.
12. }
12. Peek operation: to display info of top
element
12
Top
6
1
7
Top.name
Top.salary
…
13. Peek operation: to display info of top
element
13
1. public void Peek()
2. {
3. if (Top == null)
4. Console.WriteLine("The Stack is Empty!!");
5. else
6. Console.WriteLine("The Employee Data:n"+
7. "Name: "+Top.name+"nSalary: "+Top.salary);
8. }
14. Clear the Stack
14
Clearing the stack means that the top must
points to null.
Top
6
1
7
15. Clear the Stack
15
1. public void Clear()
2. {
3. if (Top == null)
4. Console.WriteLine("The Stack is Empty!!");
5. else
6. Top = null;
7. Length = 0;
8. }
19. Search about data
19
البيانات تراكيب مساق
إعداد العلمية المادة
/
أ
.
ا َّالفــر رفيق محمود
1. public void SearchByName(String name )
2. {
3. Employee current = Top;
4. bool flag = false;
5. while ( current != null)
6. {
7. if (name.CompareTo(current.name) == 0)
8. {
9. flag = true;
10. break;
11. }
12. current = current.next;
13. }
14. if (flag == true)
15. Console.WriteLine("Exist!!");
16. else
17. Console.WriteLine("Does not Exist!!");
18. }
20. Stack Collection
The Stack class is an implementation of the
ICollection interface that represents a LIFO
collection, or a stack.
The class is implemented in the .NET
Framework as a circular buffer, which enables
space for items pushed on the stack to be
allocated dynamically.
The default constructor is called as follows:
Stack myStack = new Stack();
Practice:
develop a full
application
using stack
class