数据结构作业——P53算法设计题(6):设计一个算法,通过一趟遍历确定长度为n的单链表中值最大的结点

时间:2025-04-15 12:11:11
/* *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; }