Topshiriq variantlariga o‟xshash bitta misolni yechish dasturini ko‟rib chiqamiz. Quyidagicha masala qo‟yilgan bo‟lsin. Ro‟yhatning maksimal elementi topilsin. Ushbu masalaning algoritmi, dasturiy kodi va natijasi quyida keltirilgan.
Ekranga menyu chiqaramiz: 1 - element qo’shish; 2 - ro’yhatni ko’rish; 3 - ro’yhat maksimalini topish; 0 - chiqish; tanlash uchun tanla o‟zgaruvchisiga qiymat so‟raymiz. 2-qadamga o‟tish.
Agar tanla=1 bo‟lsa, 3-qadamga, 2 ga teng bo‟lsa, 4-qadamga, 3 tanlansa, 6-qadamga o‟tish, 0 tanlansa dasturni yakunlash.
Navbatdagi elementni yaratish p; (p ning info maydoniga qiymat so‟rab olib yozish va ptr maydoniga NULL yozish) Agar ro‟yhat boshi ko‟rsatkichi lst=NULL bo‟lsa, lst=p va last=p; aks holda last – ro‟yhat oxirgi elementi ptr maydoniga p ni yozib, p elementni last qilib belgilaymiz. 1-qadamga o‟tamiz.
Agar lst NULL ga teng bo‟lsa, ro‟yhat bo‟shligini ekranga chiqarib, 1-qadamga o‟tish. Aks holda, p=lst va 5-qadamga o‟tish.
Agar p ning ptr maydoni NULL bo‟lmasa, p ning info maydonini ekranga chiqaramiz va keyingi elementga o‟tamiz, ya’ni p=p->ptr, 5-qadamga o‟tamiz, aks holda, 1-qadamga o‟tamiz.
max=lst->info, ya’ni max o‟zgaruvchisiga ro‟yhat 1-elementi info maydoni qiymatini o‟zlashtiramiz. p=lst va 7-qadamga o‟tish.
Agar p NULL ga teng bo‟lmasa, 8-qadamga o‟tamiz, aks holda max ni ekranga chiqaramiz va 1-qadamga o‟tamiz.
Agar max< p->info bo‟lsa, max=p->info. Keyingi elementga o‟tamiz, ya’ni p=p->ptr. 7-qadamga o‟tamiz.
Dastur kodi #include using namespace std; class Node{ public: int number; Node* next; }; int main() { Node* head = NULL; Node* lastPtr = NULL; short action = -1; while(1) { cout<<"1. element qo’shish\n"; cout<<"2. ro’yhatni ko’rish\n"; cout<<"3. ro’yhat maksimalini topish\n"; cout<<"0. chiqish\n\n"; cout<<"tanlang:"; cin>>action; if (action == 0) { system("CLS"); break;} if (action == 1) { system("CLS"); Node* ptr = new Node; int numb = -1; cout<<"son kiriting: "; cin>>numb; ptr->number = numb; ptr->next = NULL; if (head ==0) { head = ptr; lastPtr = ptr; system("CLS"); continue; } lastPtr->next = ptr; lastPtr = ptr; system("CLS"); continue; } if (action == 2){ Node* ptr = NULL; system("CLS"); if (head == 0) { cout<<"\t!!! ro’yhat bo’sh !!!\n\n"; system("PAUSE"); system("CLS"); continue; } cout<<"* * * * * ro’yhat * * * * *\n\n"; ptr = head; while (1) { cout<
number<<" "; if (ptr->next == 0)break; ptr = ptr->next; } cout<<"\n\n"; system("PAUSE"); system("CLS"); continue; } if (action == 3) { system("CLS"); Node* p = head; Node* q = newNode; Node* last = new Node; int max=p->number; q=head; while(p){ if(max
number){ max=p->number;} p=p->next; } system("CLS"); cout<<"max="< } }}