[Algorithm] Stack

BruniOS
Mar 11, 2024

--

오늘은 Stack 에 대해 알아보자

Stack

스택은 LIFO(Last In First Out) 의 특징을 가지고 있다.

즉 가장 끝에 들어간 데이터가 가장 먼저 나오는 방식이다.

public struct Stack<T> {
private var elements = [T]()
public init() {}
public mutating func pop() -> T? {
return self.elements.popLast()
}

public mutating func push(element : T) {
self.elements.append(element)
}

public func peek() -> T? {
return self.elements.last
}

public func isEmpty: Bool {
return self.elements.isEmpty
}

public var count : Int {
return self.elements.count
}
}

mutating 이란 메소드를 통해 구조체에 포함된 데이터를 수정하고 싶으면 메소드 이름 앞에 추가하면 된다.

삽입(push)

public mutating func push(element : T) {
self.elements.append(element)
}

삭제(pop)

public mutating func pop() -> T? {
return self.elements.popLast()
}

선언방식

var exampleStack = Stack<Int>()

exampleStack.push(5)
exampleStack.pop()

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

BruniOS
BruniOS

No responses yet

Write a response