資料結構實習 - 八
DESCRIPTION
資料結構實習 - 八. 中序轉後序. 藉由由左向右掃瞄中序運算式產生後序運算式,遇到運算元就直接輸出,遇到運算符號則先存入堆疊,將優先權較高者輸出。 範例: a + b * c. 後序運算式計算. 由左向右掃描,在找到運算符號前先將運算元存入堆疊,直到遇到運算符號,再從堆疊中取出所需的運算元,執行運算後,再存回堆疊。 範例: 62/3-42*+. 練習一. 請使用 linked list 的方式儲存讀入的運算元以及運算符號,並依我們自訂的優先權順序,完成一中序轉後序程式。 - PowerPoint PPT PresentationTRANSCRIPT
中序轉後序藉由由左向右掃瞄中序運算式產生後序運算式,遇到運算元就直接輸出,遇到運算符號則先存入堆疊,將優先權較高者輸出。範例: a + b * c
Token Stack
[0] [1] [2]
top output
a -1 a
+ + 0 a
b + 0 ab
* + * 1 ab
c + * 1 abc
eos -1 abc*+
op isp icp
( 0 20
) 19 19
+ 12 12
– 12 12
* 13 13
/ 13 13
% 13 13
eos 0 0
後序運算式計算由左向右掃描,在找到運算符號前先將運算元存入堆疊,直到遇到運算符號,再從堆疊中取出所需的運算元,執行運算後,再存回堆疊。範例: 62/3-42*+
Token Stack
[0] [1] [2]
Top
62/3-42*+
66 26/2 6/2 36/2-3 6/2-3 46/2-3 4 26/2-3 4*26/2-3 +4*2
010101210
練習一 請使用 linked list的方式儲存讀入的運算元以及運
算符號,並依我們自訂的優先權順序,完成一中序轉後序程式。
在程式中, link list若有 node要刪除,不可使用free(要刪除的 node)。
增加一個 list用來收集所有不需要的 node,每當需要新增 node時,便到此 list去尋找是否有人使用的node可以使用,只有在 list是空的時候, 我們使用 malloc 去建立一個新 node。
如何收集及使用已被丟棄的 node請看P .7
優先權op isp icp
( 0 20
) 19 19
+ 14 14
– 13 13
* 12 12
/ 11 11
% 10 10
eos 0 0
練習二請完成一程式,將練習一算出的後序運算式計算出答案。
Functions for Representation of Polynomials Let avail be a variable of type poly_pointer that
points to the first node in our list of freed nodes.(avail 指向”釋放的”串列的第一個 )
Instead of using malloc and free, we now use get_node and ret_node. ( 相對於 malloc 和 free, 我們現在使用 get_node 和 ret_node)
To avoid the special case of zero polynomials, we introduce a header node into each polynomial. ( 為了處理一些特別情況 , 我們在每一個多項式中加入 header node )Each polynomial, zero or nonzero, contains one
additional node.7
avail
NULLlist of freed nodes
- -
Example Polynomials with header nodes
(a) Zero polynomial
(b) 3x14 + 2x8 + 1
3 14 2 8 1 0header - -
header
Program 4.12 : get_node function
9
poly_pointer get_node(void){ /* provide a node for use */ poly_pointer node; if (avail) { node = avail; avail = avail→link; } else { node = (poly_pointer) malloc(sizeof(poly_node)); if (IS_FULL(node)) { fprintf(stderr, “The memory is full\n”); exit(1); } } return node;}
avail • • •
NULL
node1
2
Program 4.13 : ret_node function
10
void ret_node(poly_pointer ptr){ /* return a node to the available list */ ptr→link = avail; avail = ptr;}
avail • • •
NULL
ptr
12
Program 4.14 : Erasing a circular list
11
void cerase(poly_pointer *ptr){ /*erase the circular list ptr */ poly_poitner temp; if (*ptr) { temp = (*ptr)→link; (*ptr)→link = avail; avail = temp; *ptr = NULL; }}
avail • • •
NULL
prt
temp
1
2
3