1 / 11

資料結構實習 - 八

資料結構實習 - 八. 中序轉後序. 藉由由左向右掃瞄中序運算式產生後序運算式,遇到運算元就直接輸出,遇到運算符號則先存入堆疊,將優先權較高者輸出。 範例: a + b * c. 後序運算式計算. 由左向右掃描,在找到運算符號前先將運算元存入堆疊,直到遇到運算符號,再從堆疊中取出所需的運算元,執行運算後,再存回堆疊。 範例: 62/3-42*+. 練習一. 請使用 linked list 的方式儲存讀入的運算元以及運算符號,並依我們自訂的優先權順序,完成一中序轉後序程式。

Download Presentation

資料結構實習 - 八

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 資料結構實習-八

  2. 中序轉後序 • 藉由由左向右掃瞄中序運算式產生後序運算式,遇到運算元就直接輸出,遇到運算符號則先存入堆疊,將優先權較高者輸出。 • 範例:a + b * c

  3. 後序運算式計算 • 由左向右掃描,在找到運算符號前先將運算元存入堆疊,直到遇到運算符號,再從堆疊中取出所需的運算元,執行運算後,再存回堆疊。 • 範例:62/3-42*+

  4. 練習一 • 請使用linked list的方式儲存讀入的運算元以及運算符號,並依我們自訂的優先權順序,完成一中序轉後序程式。 • 在程式中,link list若有node要刪除,不可使用free(要刪除的node)。 • 增加一個list用來收集所有不需要的node,每當需要新增node時,便到此list去尋找是否有人使用的node可以使用,只有在list是空的時候,我們使用 malloc 去建立一個新node。 • 如何收集及使用已被丟棄的node請看P.7

  5. 優先權

  6. 練習二 • 請完成一程式,將練習一算出的後序運算式計算出答案。

  7. 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. avail list of freed nodes NULL 7

  8. - 3 2 1 - - 14 8 0 - Example Polynomials with header nodes header (a) Zero polynomial header (b) 3x14 + 2x8+ 1

  9. Program 4.12 : get_node function 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; } node 1 avail • •• 2 NULL 9

  10. Program 4.13 : ret_node function void ret_node(poly_pointer ptr) { /* return a node to the available list */ ptr→link = avail; avail = ptr; } ptr 1 2 avail • •• NULL 10

  11. Program 4.14 : Erasing a circular list 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; } } temp 1 prt 2 3 avail • •• NULL 11

More Related