设计一个算法,通过一趟遍历确定长度为n的单链表中值最大的结点。

xiaoxiao2025-04-12  24

语言:C++

#include <iostream> using namespace std; typedef int Elemtype; typedef struct LNode { Elemtype data; struct LNode *next; }LNode,*LinkList; //尾插法 void CreateList(LinkList &L,int n) { LNode *p;int i; LNode *r; L=new LNode; L->next=NULL; r=L; for(i=0;i<n;++i) { p=new LNode; cin>>p->data; p->next=NULL;r->next=p; r=p; } } //输出整个单链表 void display(LinkList L) { LNode *p; p=L->next; cout<<"("; while(p) {cout<<p->data<<" "; p=p->next;} cout<<")"<<endl; } //找最大值 int MaxList(LinkList L,Elemtype &e) { LNode *p; p=L->next; e=p->data; while(p->next) {if((p->next->data)>e) e=p->next->data; p=p->next; } return e; } //主函数 int main() { LinkList L;int n;Elemtype e;int max; cout<<"请输入需要创建单链表A的长度:"<<endl; cin>>n; cout<<"请依次输入需要存入的数据(尾插法):"<<endl; CreateList(L,n); cout<<"单链表L为:"; display(L); max=MaxList(L,e); cout<<"最大值为:"<<max<<endl; return 0; }

 

转载请注明原文地址: https://www.6miu.com/read-5028076.html

最新回复(0)