Stack ADT Abstract Data Type... Stack Implementation in C• What is .h file?... Stack Implementation in C#define maxsize=5;... Stack Implementation in CInit... Stack Implementation in CPu
Trang 1by Le Quy Loc Information Technology Faculty
DUT
Trang 3Stack ADT (Abstract Data Type)
Trang 4Stack
Trang 5Design Stack
Trang 6Push An Element Into a Stack
• Algorithm
1 If stack is still empty
1.1 Save the element to the top of stack 1.2 Increase the number of elements by 1
top
1 5
7
top =2 top=3
Trang 7Stack Implementation in C
• What is h file?
Trang 8Stack Implementation in C
#define maxsize=5;
Trang 9Stack
Implementation
in C
Trang 10Stack Implementation in C
Init
Trang 11Stack Implementation in C
Push
Trang 12Stack Implementation in C
Pop
Trang 13Stack Implementation in C
Empty
Trang 14Exercises
Trang 15Determine the values of stack and top after each commands and what are printed in the program?
1 int top, element;
2 intstack[10];
3 int x, y, z;
4 x = 0;
5 y = 5;
6 z = y / 2;
7 init(&top); 8 push(stack, &top, x);
9 push(stack, &top, y);
10 z = pop(stack, &top);
11 push(stack, &top, x+1); 12 push(stack, &top, y);
13 push(stack, &top, 3);
14 while (!empty(&top))
15 {
16 z = pop(stack, &top); 17 printf(“%d ”, z);
18 }
19 printf("x = %d",x);
20 printf(“y = %d”,y);
21 printf("z = %d",z);
Trang 16Using the stack operations, write functions to
1 Copy data from a stack to another stack
2 Sum of negative elements
3 Delete all elements equal x in a stack
4 Convert decimal to binary
Trang 17Homework
Trang 18Convert infix expression to postfix
expression
• Write a function to calculate
– (3 + 4)*5
– 3 + (4 - 2 + (12 – 6)/2)*6 + 8 * 3^2
Trang 19Convert infix expression to postfix
expression
• Infix expression: operators between operands
– Good: easy to read for human
– Bad: difficult for computer to calculate
Trang 20Convert infix expression to postfix
Trang 21Convert infix expression to postfix