
思路:
- 设单链表首个元素为最大值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;
}
运行结果如下: