Data structure: Stack and Queue

Grassroot Engineer
2 min readJan 29, 2020

--

อันนี้จะเป็นเรื่อง Data structure นะคับ (ไม่ใช่ Data type) สำหรับ Stack and Queue ต่างกันยังไง มาลองทบทวนกันนะคับ

สำหรับ Stack จะเป็นแบบ LIFO (Last In-First Out) คือ เข้าทีหลัง ออกก่อนนะคับ คำสั่งที่เกี่ยวข้องคือ push, pop

https://dev.to/rinsama77/data-structure-stack-and-queue-4ecd

อันนี้เป็นตัวอย่าง Using lists as Stacks นะคับ

append = push นะคับ, pop คือนำ data จาก list ออก
Result จะเป็นแบบนี้นะคับ เป็นการ pop ข้อมูลจากข้อมูลล่าสุดออกมา

มาต่อกันที่ Queue นะคับ ซึ่งจะเป็นแบบ FITO (First In-First Out) คือ แบบยุติธรรมเหมือนเราเข้าคิวเลย คือ เข้าก่อนออกก่อน มาทีหลังก้อออกทีหลัง คำสั่งที่เกี่ยวข้องคือ enqueue และ dequeue

https://dev.to/rinsama77/data-structure-stack-and-queue-4ecd

Basic operations on a queue:
1. Enque/Add/Put: Insert a data item on the back or rear of the queue.
2. Deque/Delete/Get: Remove an item from the front of the queue.
3. Peek: Read the value of an item from the front of the queue without removing it.

มาดู code ตัวอย่างจากกันนะคับ สำหรับ queue เราต้อง import collection ในส่วนของ queue เข้ามาด้วยนะคับ ตามนี้

ใช้ .popleft() สำหรับนำค่าออกมาทีละค่า จากด้านซ้ายนะคับ (นั่นคือค่าที่มาก่อนนั่นเอง)
Result after running.

แล้วพบกันใหม่ตอนถัดไปครับ

--

--

Grassroot Engineer
Grassroot Engineer

Written by Grassroot Engineer

ATM engineer who is interested in CODING and believe in EFFORT. — https://grassrootengineer.com

No responses yet