Mavzu: Ro’yxatlar va navbatlar Reja: I. Kirish


Download 37.86 Kb.
bet8/9
Sana14.05.2023
Hajmi37.86 Kb.
#1458471
1   2   3   4   5   6   7   8   9
Bog'liq
Mavzu

Navbat
Queue klassi FIFO ("birinchi kiruvchi, birinchi chiqadi") algoritmiga muvofiq ishlaydigan oddiy navbatni ifodalaydi.
Navbat yarating
Navbat yaratish uchun uchta navbat konstruktoridan birini ishlatishingiz mumkin. Avvalo, siz bo'sh navbat yaratishingiz mumkin:




Queue people = new Queue();

Bo'sh navbatni yaratishda siz navbatning sig'imini belgilashingiz mumkin:




Queue people = new Queue(16

Shuningdek, navbatni boshqa to'plamdagi elementlar yoki massiv bilan boshlashingiz mumkin:




var employees = new List { "Tom", "Sam", "Bob" };
Queue people = new Queue(employees);
foreach (var person in people) Console.WriteLine(person);
Console.WriteLine(people.Count); // 3

Navbatni takrorlash uchun standart foreach loopidan foydalanishingiz mumkin .
Navbatdagi elementlar sonini olish uchun sinf Count xususiyatini belgilaydi .
Navbat turlari
Sinfda Queuequyidagi usullar mavjud:

  • void Clear() : navbatni tozalaydi

  • bool Contains(T item)true : agar element navbatda bo'lsa, qaytaradi

  • T Dequeue() : navbatning birinchi elementini oladi va qaytaradi

  • void Enqueue(T element) : navbat oxiriga element qo'shadi

  • T Peek() : oddiygina birinchi elementni navbat boshidan olib tashlamasdan qaytaradi

Amalda navbatdan foydalanishni ko'rib chiqamiz:

var people = new Queue();
// elementlarni qo'shish
people.Enqueue("Tom"); // people = { Tom }
people.Enqueue("Bob"); // people = { Tom, Bob }
people.Enqueue("Sam"); // people = { Tom, Bob, Sam }
// elementni navbatning boshidan boshlab oling
var firstPerson = people.Peek();
Console.WriteLine(firstPerson); // Tom
// elementlarni olib tashlash
var person1 = people.Dequeue(); // people = { Bob, Sam }
Console.WriteLine(person1); // Tom
var person2 = people.Dequeue(); // people = { Sam }
Console.WriteLine(person2); // Bob
var person3 = people.Dequeue(); // people = { }
Console.WriteLine(person3); // Sam

Shuni ta'kidlash kerakki, agar Peek yoki Dequeue usullaridan foydalangan holda biz bo'sh bo'lgan navbatning birinchi elementini olishga harakat qilsak, dastur istisno qiladi. Shunga ko'ra, elementni olishdan oldin biz navbatdagi elementlar sonini tekshirishimiz mumkin:

if(people.Count > 0)
{
var person = people.Peek();
people.Dequeue();
}

Yoki siz bir nechta usullardan foydalanishingiz mumkin:
1   2   3   4   5   6   7   8   9




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling