思路:
- 設單鏈表首個元素為最大值max
- 通過遍歷元素,與最大值max作比較,將較大值附給max
- 輸出最大值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;
}
運行結果如下: