Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 21 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
21
Dung lượng
456,98 KB
Nội dung
Stack by Le Quy Loc Information Technology Faculty DUT Examples • Stack of discs • Put and remove batteries from a flashlight • Undo action First In Last Out (FILO) Stack ADT (Abstract Data Type) • Data organization – The set of the same-type elements – FILO • Operations – Push – Pop – Top – isEmpty Stack Design Stack Push An Element Into a Stack • Algorithm If stack is still empty 1.1 Save the element to the top of stack 1.2 Increase the number of elements by top top =2 top=3 Stack Implementation in C • What is h file? Stack Implementation in C #define maxsize=5; Stack Implementation in C Stack Implementation in C Init Stack Implementation in C Push Stack Implementation in C Pop Stack Implementation in C Empty Exercises Determine the values of stack and top after each commands and what are printed in the program? int top, element; 10 11 12 13 14 15 16 17 18 19 20 21 int stack[10]; int x, y, z; x = 0; y = 5; z = y / 2; init(&top); push(stack, &top, x); push(stack, &top, y); z = pop(stack, &top); push(stack, &top, x+1); push(stack, &top, y); push(stack, &top, 3); while (!empty(&top)) { z = pop(stack, &top); printf(“%d ”, z); } printf("x = %d",x); printf(“y = %d”,y); printf("z = %d",z); Exercises Using the stack operations, write functions to Copy data from a stack to another stack Sum of negative elements Delete all elements equal x in a stack Convert decimal to binary Homework Convert infix expression to postfix expression • Write a function to calculate – (3 + 4)*5 – + (4 - + (12 – 6)/2)*6 + * 3^2 Convert infix expression to postfix expression • Infix expression: operators between operands – Good: easy to read for human – Bad: difficult for computer to calculate Convert infix expression to postfix expression • Suffix expression –x+y xy+ – x*y x y * – x-y x y – x/y x y / – x + (y-z) x y z - + Convert infix expression to postfix expression • Suggest algorithm to convert infix expression to suffix expression • Assume that you only know basic arithmetic operators – Calculate the expression • +-*/()