StackとQueueの説明 (一応)
項目 | スタック(Stack) | キュー(Queue) |
---|
イメージ | お皿を重ねるように積み上げる | バスを待つ列 |
データの出し入れ順 | 後入れ先出し(LIFO: Last In, First Out) | 先入れ先出し(FIFO: First In, First Out) |
追加(入れる) | 上に追加する(push) | 後ろに追加する(enqueue) |
削除(取り出す) | 上から取り出す(pop) | 前から取り出す(dequeue) |
使用例 | 戻るボタンの履歴、関数の呼び出し履歴など | 印刷キュー、タスク処理、接客待ちなど |
Swiftの操作例 | stack.append() / stack.popLast() | queue.append() / queue.removeFirst() |
実装
import SwiftUI
struct HomeView: View {
var body: some View {
TabView {
StackView()
.tabItem {
Label("Stack", systemImage: "square.stack.3d.up")
}
QueueView()
.tabItem {
Label("Queue", systemImage: "line.3.horizontal")
}
}
}
}
// MARK: - Stack (LIFO)
struct StackView: View {
@State private var stack: [Int] = []
@State private var counter = 1
var body: some View {
VStack(spacing: 20) {
Text("Stack (LIFO)").font(.title).bold()
VStack {
// [1, 2, 3, 4, 5]の順をReverseする
ForEach(stack.reversed(), id: \.self) { item in
Text("📦 \(item)")
.frame(width: 120, height: 60)
.background(Color.blue.opacity(0.8))
.foregroundColor(.white)
.cornerRadius(8)
.transition(.move(edge: .top).combined(with: .opacity))
}
}
.animation(.easeInOut, value: stack)
HStack {
Button("Push 📥") {
withAnimation {
stack.append(counter)
counter += 1
}
}
.buttonStyle(.borderedProminent)
Button("Pop 📤") {
withAnimation {
_ = stack.popLast()
}
}
.buttonStyle(.bordered)
.disabled(stack.isEmpty)
}
}
.padding()
}
}
// MARK: - Queue (FIFO)
struct QueueView: View {
@State private var queue: [Int] = []
@State private var counter = 1
var body: some View {
VStack(spacing: 20) {
Text("Queue (FIFO)").font(.title).bold()
HStack {
ForEach(queue, id: \.self) { item in
Text("📦 \(item)")
.frame(width: 50, height: 50)
.background(Color.green.opacity(0.8))
.foregroundColor(.white)
.cornerRadius(10)
.transition(.move(edge: .trailing).combined(with: .opacity))
}
}
.animation(.easeInOut, value: queue)
HStack {
Button("Enqueue 📥") {
withAnimation {
queue.append(counter)
counter += 1
}
}
.buttonStyle(.borderedProminent)
Button("Dequeue 📤") {
withAnimation {
if !queue.isEmpty {
queue.removeFirst()
}
}
}
.buttonStyle(.bordered)
.disabled(queue.isEmpty)
}
}
.padding()
}
}