數據結構作業——P53算法設計題(6):設計一個算法,通過一趟遍歷確定長度為n的單鏈表中值最大的結點


思路:

  1. 設單鏈表首個元素為最大值max
  2. 通過遍歷元素,與最大值max作比較,將較大值附給max
  3. 輸出最大值max

算法:

/* *title:P53頁程序設計第6題 *writer:weiyuexin *data:2020-9-26 */

#include<iostream>

using namespace std;

#define ElemType int

typedef struct LNode{
    ElemType data;   //定義數據域
    struct LNode *next;
}LNode,*LinkList;

void CreateList(LinkList &L){

    L = new LNode;     //申請存儲空間
    L->next = NULL;

    int n;
    cout<<"請輸入單鏈表的長度:"<<endl;
    cin>>n;

    LinkList r = L;

    cout<<"請輸入單鏈表的數據元素:"<<endl;
    for(int i=0;i<n;i++){
        LinkList p = new LNode;
        cin>>p->data;
        p->next = NULL;
        r->next = p;
        r = p;
    }
}

void Display(LinkList L){
    LinkList p = L->next;
    while(p){
        cout<<p->data<<" ";
        p = p->next;
    }
    cout<<endl;
}

void FindMax(LinkList L){
    int max = L->next->data;
    LinkList p = L->next;
    int i = 1,maxnode;
    while(p){
        if(p->data > max){
            max = p->data;
            maxnode = i;
        }
        p = p->next;
        ++i;
    }
    cout<<max<<" ";
    cout<<maxnode<<endl;
}
int main(){
    cout<<"P53頁第7題:"<<endl;
    cout<<endl;
    LinkList L;
    CreateList(L);
    cout<<"初始化后的單鏈表為:"<<endl;
    Display(L);
    cout<<"該單鏈表中數據元素最大值以及最大值對應的結點分別為:"<<endl;
    FindMax(L);
    return 0;
}

運行結果如下:
在這里插入圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM