190 likes | 420 Views
Stack & Queue. Winter-Camp-2011 CSIE.NTNU. N.S.Lin@csie.ntnu@Taiwan. CC – 非商業性 – 相同方式. Stack. 一種串列式資料結構 LIFO (Last In First Out). Stack Sample. Make a Stack. -1. 0. 1. 2. 3. 4. 5. 6. 7. #define SIZE 8 int my_stack[SIZE]; int pointer = -1. if (pointer < 0) null.
E N D
Stack & Queue Winter-Camp-2011 CSIE.NTNU N.S.Lin@csie.ntnu@Taiwan CC– 非商業性 – 相同方式
Stack • 一種串列式資料結構 • LIFO(Last In First Out)
Make a Stack -1 0 1 2 3 4 5 6 7 #define SIZE 8 int my_stack[SIZE]; int pointer = -1 if (pointer < 0) null. if (pointer == SIZE) full.
Queue • 一種串列式資料結構 • FIFO(First In First Out)
Make a Queue 0 1 2 3 4 5 6 7 if (front == rear) null. if (rear == SIZE) full.
Stack Applications • LISP functions • Infix to Postfix
LISP Functions ( ( () () ) ) oddp - 5 2 + * 2 3
LISP Functions ( ( () () ) ) - 將左括號放入stack, 看到右括號就從stack拿出一個左括號 ( ( ( (
Infix to Postfix • Infix : (1 + 2) * 3 + 4 • Postfix : 1 2 + 3 * 4 +
Infix to Postfix • Usea Stack • Output the numbers • Push operators into the stack • If there are operators having higher(or equal) precedence, pop them. • When read ) , pop all operators until pop a ( .
Infix to Postfix • Operator Precedence • Outside : (> * = / > + = - • Inside : * = / > + = - > (
Infix to Postfix • ( 1 + 2 ) * 3 / 4 4 / 1 2 + 3 * + / ( *
Queue Applications • BFS
Test Yourself • 673 - Parentheses Balance • 271 - Simply Syntax • 727 - Equation
Test Yourself Practice: Use a Circular Queue Sample Input: 100 200 -1 4 20 -1 -1 10 -1 0 Sample Output: 100 200 4 20