0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swift スタックを理解する

Posted at

スタックとは

LIFOを実装した構造体のことくをいう。一番最後にいれたものが一番先にでる(逆がFIFOであるキュー)

スタックの3つの機能
1,pop スタックの一番上にあるデータを先に出す
2,push スタックの一番上にデータを入れる
3,peek スタックの一番上にあるデータを読み取る

お魚.swift

 //swift
public struct Stack<T> {
    
    var array = [T]()

  //中身が空かどうか調べる。
  public var isEmpty: Bool {
    return array.isEmpty
  }

  //スタックの一番上にプッシュする。 構造体を変更するのでmutating が必要
  public mutating func push(_ element: T) {
    array.append(element)
  }

  //スタックの一番上を取り出す。 構造体を変更するのでmutatingが必要
  public mutating func pop() -> T? {
    return array.popLast()
  }

  //スタックの一番上にあるデータを読み取る。
  public var peek: T? {
    return array.last
  }
}

//スタック構造を利用して配列を逆に返す
 func reverse(arr:[String])->[String]{
   var stack = Stack(array:[]);
   for i in 0..<arr.count {
    stack.push(arr[i])
  }
    //下記、配列の数だけ繰り返し処理してreversedに入れていく処理
    var reversed:[String] = [];//reverse用のからの配列を設定
    while(stack.peek() != nil { //nilではない限りはループ処理させる
        reversed.push(stack.pop());//スタックの最後の要素をプッシュしていく
    }
    return reversed;
}

// スタックを作成する
var stackOfFish = Stack(array: ["🐟", "🐠", "🐡", "🐳","🐬"])


// サメさんを末尾にプッシュする 
stackOfFish.push("🦈")

//サメさんを末尾から取り出す
stackOfFish.pop()

//イルカさんが読み取れる
stackOfFish.peer

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?