1. 程式人生 > >設計一個演算法,通過一趟遍歷確定長度為n的單鏈表中值最大的結點。

設計一個演算法,通過一趟遍歷確定長度為n的單鏈表中值最大的結點。

語言: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;
}