第四周--專案3單鏈表的應用(3)
阿新 • • 發佈:2019-02-08
* Copyright (c++) 2015 煙臺大學計算機學院
* All right reserved.
* 檔名稱:p3.cpp
* 作 者: 商文軻
* 完成日期:2015年10月15日
* 版 本 號:v1.9
* 問題描述:設計一個演算法,判斷單鏈表L是否是遞增的。實現這個演算法,並完成測試。
.*/
本程式採用多組織結構,利用單鏈表演算法庫。#include "linklist.h" bool increase(LinkList *L) { LinkList *p = L->next, *q; //p指向第1個數據節點 if(p != NULL) { while(p->next != NULL) { q = p->next; //q是p的後繼 if (q->data > p->data) //只要是遞增的,就繼續考察其後繼 p = q; else return false; //只要有一個不是後繼大於前驅,便不是遞增 } } return true; } int main() { LinkList *A, *B; int i; ElemType a[]= {1, 3, 2, 9}; ElemType b[]= {0, 4, 5 ,6, 7, 8}; InitList(A); for(i=3; i>=0; i--) ListInsert(A, 1, a[i]); InitList(B); for(i=5; i>=0; i--) ListInsert(B, 1, b[i]); printf("A: %c\n", increase(A)?'Y':'N'); printf("B: %c\n", increase(B)?'Y':'N'); DestroyList(A); DestroyList(B); return 0; }
總結:比較遞增函式中只需比較前驅後繼元素的大小即可。主函式實現測試功能時利用插入建立新連結串列。