一步一步寫演算法(之prim演算法 下)

來源:互聯網
上載者:User

【 聲明:著作權,歡迎轉載,請勿用於商業用途。  聯絡信箱:feixiaoxing @163.com】

    前兩篇部落格我們討論了prim最小產生樹的演算法,熟悉了基本的流程。基本上來說,我們是按照自上而下的順序來編寫代碼的。首先我們搭建一個架構,然後一步一步完成其中的每一個子功能,這樣最後構成一個完成prim演算法計算過程。

    f)將DIR_LINE隊列中不符合的資料刪除,主要是雙節點都已經訪問過的DIR_LINE資料。

void delete_unvalid_line_from_list(DIR_LINE** ppHead, MINI_GENERATE_TREE* pMiniTree){DIR_LINE* prev;DIR_LINE* pcur;STATUS result;prev = NULL;pcur = *ppHead;while(pcur){if(!check_valid_for_line(pcur, pMiniTree)){result = delete_line_from_queue(ppHead, pcur);assert(TRUE == result);if(NULL == prev)pcur = *ppHead;elsepcur = prev->next;continue;}prev = pcur;pcur = pcur->next;}return;}

    g) 在f)函數中使用了判定DIR_LINE合法性的函數,我們需要完善一下。

int check_valid_for_line(DIR_LINE* pDirLine, MINI_GENERATE_TREE* pMiniTree){int index;int flag_start;int flag_end;flag_start = 0;flag_end = 0;for(index = 0; index < pMiniTree->node_num; index ++){if(pDirLine->start == pMiniTree->pNode[index]){flag_start = 1;break;}}for(index = 0; index < pMiniTree->node_num; index ++){if(pDirLine->end == pMiniTree->pNode[index]){flag_end = 1;break;}}return (1 == flag_start && 1 == flag_end) ? 0 : 1;}

    h) 最後就是對當前已經入隊的DIR_LINE資料排序,其實就是鏈表排序 

void insert_for_sort_operation(DIR_LINE** ppNode, DIR_LINE* pNode)  {      DIR_LINE* prev;      DIR_LINE* cur;      /* 在第一個資料之前插入pNode */      if(pNode->weight < (*ppNode)->weight){          pNode->next = *ppNode;          *ppNode = pNode;          return;      }      cur = *ppNode;      while(cur){          if(pNode->weight < cur->weight)              break;          prev = cur;          cur = cur->next;      }      pNode->next = prev->next;      prev->next = pNode;      return;  } void sort_for_line_list(DIR_LINE** ppNode){DIR_LINE* prev;DIR_LINE* curr;if(NULL == ppNode || NULL == *ppNode)return;curr = (*ppNode) ->next;(*ppNode) ->next = NULL;while(curr){prev = curr;curr = curr->next;insert_for_sort_operation(ppNode, prev);}}

演算法總結:

    1)演算法本身還有改進的空間,比如是不是記憶體配置上每一次都要重建DIR_LINE隊列有待商榷

    2)演算法編寫不是一部就位的,中間有反覆更有刪改,寫四五次是很正常的事情

    3)編寫代碼的時候最好做到邊修改、邊測試,這樣可以一方面增加代碼的健壯度,一方面還能提高自己的信心

    4)如果存在可能,可以複用以前寫過的、穩定的演算法代碼,比如說排序、尋找、堆棧、二叉樹之類的代碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.