SlideShare a Scribd company logo
SWIFT
Data Structure -
Linked List
Bill Kim(김정훈) | ibillkim@gmail.com
목차
•Linked List
•Concept
•Features
•Implementation
•References
Linked List
링크드 리스트(Linked List)는 순차적으로 모인 데이터의 모음으로
서 다음 차례의 노드 주소를 가지고 있는 형태를 가집니다.
가지고 있는 노드의 주소 형태에 따라서 아래의 두 가지 유형을 나
타낼 수 있습니다.
Singly Linked List :
다음 노드(Next Node)의 주소만 가지는 리스트
Double Linked List :
다음 노드 및 이전 노드(Previous Node)의 주소를 가지는 리스트
Linked List를 사용하기 위해서는 시작과 끝의 주소를 알아야 하는
데 이를 head와 tail이라 부릅니다.
Concept
Linked List의 기본 동작 흐름은 아래와 같습니다.
Features
Linked List의 특징을 살펴보면 아래와 같습니다.
- 데이터를 순차적으로 동적 저장합니다.
- 데이터 중복 저장을 허용합니다.
- 총 길이의 제한이 없습니다.
- 특정 노드의 주소를 모르면 직접 접근이 불가합니다.
Implementation
Swift를 활용하여 Linked List 를 구현해보겠습니다.
우선 필요한 메소드는 아래와 같습니다.
- init : 리스트를 초기화하는 함수
- insert : 데이터 입력(마지막 혹은 특정 노드 위치)
- remove : 특정 노드 삭제
- removeLast : 마지막 데이터 삭제
- removeAll : 모든 데이터 삭제
- count : 현재 리스트의 크기를 반환
- isEmpty : 현재 리스트의 크기가 비어있는지 체크
Implementation
가장 데이터의 기본이 되는 Node 클래스 입니다.
해당 Node 클래스는 모든 데이터 형식을 받을 수 있도록
Generic 형태로 구현이 되어 있습니다.
class LinkedListNode<T> {
var value: T
var next: LinkedListNode?
weak var previous: LinkedListNode?
public init(value: T) {
self.value = value
}
}
Implementation
class LinkedList<T> {
typealias Node = LinkedListNode<T>
private var head: Node?
private var tail: Node?
public init() {
head = nil
tail = nil
}
public var isEmpty: Bool {
return head == nil
}
public var first: Node? {
return head
}
public var last: Node? {
return tail
}
....
Implementation
public func node(at index: Int) -> Node? {
if index >= 0 {
var node = head
var i = index
while node != nil {
if i == 0 { return node }
i -= 1
node = node!.next
}
}
return nil
}
public func insert(_ value: T) {
let newNode = Node(value: value)
if let tailNode = tail {
newNode.previous = tailNode
tailNode.next = newNode
} else {
head = newNode
}
tail = newNode
}
....
Implementation
public func insert(_ node: Node, at index: Int) {
if index == 0,
tail == nil {
head = node
tail = node
} else {
guard let nodeAtIndex = self.node(at: index) else {
print("Index out of bounds.")
return
}
if nodeAtIndex.previous == nil {
head = node
}
node.previous = nodeAtIndex.previous
nodeAtIndex.previous?.next = node
node.next = nodeAtIndex
nodeAtIndex.previous = node
}
}
....
Implementation
public func removeAll() {
head = nil
tail = nil
}
public func removeLast() -> T {
return remove(node: last!)
}
public func remove(node: Node) -> T {
let prev = node.previous
let next = node.next
if let prev = prev {
prev.next = next
} else {
head = next
}
next?.previous = prev
node.previous = nil
node.next = nil
return node.value
}
....
Implementation
public func count() -> Int {
guard var node = head else {
return 0
}
var count = 1
while let next = node.next {
node = next
count += 1
}
return count
}
....
Implementation
public var toString : String {
var s = "["
var node = head
while node != nil {
s += "(node!.value)"
node = node!.next
if node != nil { s += ", " }
}
return s + "]"
}
struct LinkedListIterator : IteratorProtocol {
let linkedList: LinkedList
var current: Node?
init(_ linkedList: LinkedList) {
self.linkedList = linkedList
self.current = linkedList.head
}
mutating func next() -> Node? {
guard let thisCurrent = current else { return nil }
current = thisCurrent.next
return thisCurrent
}
}
}
Implementation
extension LinkedList : Sequence {
func makeIterator() -> LinkedListIterator {
return LinkedListIterator(self)
}
}
// 사용 예시
let list:LinkedList<Int> = LinkedList<Int>()
list.insert(1)
list.insert(2)
list.insert(3)
list.insert(4)
list.insert(5)
// 현재 리스트 카운트 : 5
print(list.count())
for node in list {
print(node.value)
// 1
// 2
// 3
// 4
// 5
}
References
[1] 스위프트 : 연결리스트 (1 / 3) : #LinkedList :
#DataStructrue : #자료구조: #swift : https://the-brain-of-
sic2.tistory.com/14
[2] 스위프트 : 연결리스트 (2 / 3) : #LinkedList : #값 추가하기,
push, append : #값 삽입하기,insert: #swift : https://the-
brain-of-sic2.tistory.com/15
[3] [Swift 자료구조 ch08] Linked List : https://
kor45cw.tistory.com/244
[4] Swift로 자료구조, 알고리즘 공부하기 (4) - Linked List :
https://kor45cw.tistory.com/4
[5] Data Structure) 링크드 리스트(Linked List) in Swift :
https://atelier-chez-moi.tistory.com/90
References
[6] Data Structure (자료구조) : https://opentutorials.org/module/
1335
[7] Linked List : https://woongsios.tistory.com/49
[8] Data Structure 데이터 구조 : https://m.blog.naver.com/
PostView.nhn?
blogId=jdub7138&logNo=220957839382&proxyReferer=https:
%2F%2Fwww.google.com%2F
[9] C <18>. 연결리스트 (Linked list) – 자료구조(1) : https://
blog.yagom.net/249/
[10] [Data Structure] 자료구조 - 연결 리스트(Linked List) - 단순 연결
리스트(Singly / Linear Linked List) : https://palpit.tistory.com/
141
Thank you!

More Related Content

What's hot (10)

데이터 분석 4 - 나만의 배열 기반 LIST, MyArrayList를 만들어보자
데이터 분석 4 - 나만의 배열 기반 LIST, MyArrayList를 만들어보자
Jaewook Byun
 
데이터 분석 6 - 나만의 배열 기반 LIST, MyLinkedList를 만들어보자
데이터 분석 6 - 나만의 배열 기반 LIST, MyLinkedList를 만들어보자
Jaewook Byun
 
Data Structures
Data Structures
skku_npc
 
Binary Search
Binary Search
skku_npc
 
데이터 분석 1 - 소개
데이터 분석 1 - 소개
Jaewook Byun
 
데이터 분석 5 - Java Collection Framework - LinkedList 파헤치기
데이터 분석 5 - Java Collection Framework - LinkedList 파헤치기
Jaewook Byun
 
My sql connector.c++ 기본 가이드
My sql connector.c++ 기본 가이드
ChungYi1
 
연결 리스트(기초)
연결 리스트(기초)
Lee Geonhee
 
Swift 0x17 generics
Swift 0x17 generics
Hyun Jin Moon
 
데이터 분석 3 - Java Collection Framework와 ArrayList
데이터 분석 3 - Java Collection Framework와 ArrayList
Jaewook Byun
 
데이터 분석 4 - 나만의 배열 기반 LIST, MyArrayList를 만들어보자
데이터 분석 4 - 나만의 배열 기반 LIST, MyArrayList를 만들어보자
Jaewook Byun
 
데이터 분석 6 - 나만의 배열 기반 LIST, MyLinkedList를 만들어보자
데이터 분석 6 - 나만의 배열 기반 LIST, MyLinkedList를 만들어보자
Jaewook Byun
 
Data Structures
Data Structures
skku_npc
 
Binary Search
Binary Search
skku_npc
 
데이터 분석 1 - 소개
데이터 분석 1 - 소개
Jaewook Byun
 
데이터 분석 5 - Java Collection Framework - LinkedList 파헤치기
데이터 분석 5 - Java Collection Framework - LinkedList 파헤치기
Jaewook Byun
 
My sql connector.c++ 기본 가이드
My sql connector.c++ 기본 가이드
ChungYi1
 
연결 리스트(기초)
연결 리스트(기초)
Lee Geonhee
 
데이터 분석 3 - Java Collection Framework와 ArrayList
데이터 분석 3 - Java Collection Framework와 ArrayList
Jaewook Byun
 

Similar to [Swift] Data Structure - Linked List (20)

[Swift] Data Structure - Stack
[Swift] Data Structure - Stack
Bill Kim
 
[Swift] Data Structure - Graph(BFS)
[Swift] Data Structure - Graph(BFS)
Bill Kim
 
연결 자료구조
연결 자료구조
Choonghyun Yang
 
[Swift] Data Structure - Graph(DFS)
[Swift] Data Structure - Graph(DFS)
Bill Kim
 
[Swift] Data Structure - Graph
[Swift] Data Structure - Graph
Bill Kim
 
리스트
리스트
Samuel Lee
 
[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search Tree
Bill Kim
 
Basic Data Structure stack&queue
Basic Data Structure stack&queue
Namhoon Kim
 
이산수학 C1 프로젝트 4
이산수학 C1 프로젝트 4
pkok15
 
Swift 3 Programming for iOS : class and structure
Swift 3 Programming for iOS : class and structure
Kwang Woo NAM
 
[Swift] Data Structure - AVL
[Swift] Data Structure - AVL
Bill Kim
 
연결리스트 박진호
연결리스트 박진호
jinho park
 
[Swift] Data Structure - Heap
[Swift] Data Structure - Heap
Bill Kim
 
GraphQL 적용기
GraphQL 적용기
Changwan Jun
 
이산수학 C1 프로젝트 5
이산수학 C1 프로젝트 5
pkok15
 
자료구조 04 최종 보고서
자료구조 04 최종 보고서
pkok15
 
자료구조 Project3
자료구조 Project3
KoChungWook
 
[Swift] Data Structure - Stack
[Swift] Data Structure - Stack
Bill Kim
 
[Swift] Data Structure - Graph(BFS)
[Swift] Data Structure - Graph(BFS)
Bill Kim
 
[Swift] Data Structure - Graph(DFS)
[Swift] Data Structure - Graph(DFS)
Bill Kim
 
[Swift] Data Structure - Graph
[Swift] Data Structure - Graph
Bill Kim
 
[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search Tree
Bill Kim
 
Basic Data Structure stack&queue
Basic Data Structure stack&queue
Namhoon Kim
 
이산수학 C1 프로젝트 4
이산수학 C1 프로젝트 4
pkok15
 
Swift 3 Programming for iOS : class and structure
Swift 3 Programming for iOS : class and structure
Kwang Woo NAM
 
[Swift] Data Structure - AVL
[Swift] Data Structure - AVL
Bill Kim
 
연결리스트 박진호
연결리스트 박진호
jinho park
 
[Swift] Data Structure - Heap
[Swift] Data Structure - Heap
Bill Kim
 
이산수학 C1 프로젝트 5
이산수학 C1 프로젝트 5
pkok15
 
자료구조 04 최종 보고서
자료구조 04 최종 보고서
pkok15
 
자료구조 Project3
자료구조 Project3
KoChungWook
 
Ad

More from Bill Kim (19)

[Algorithm] Sorting Comparison
[Algorithm] Sorting Comparison
Bill Kim
 
[Algorithm] Big O Notation
[Algorithm] Big O Notation
Bill Kim
 
[Algorithm] Shell Sort
[Algorithm] Shell Sort
Bill Kim
 
[Algorithm] Radix Sort
[Algorithm] Radix Sort
Bill Kim
 
[Algorithm] Quick Sort
[Algorithm] Quick Sort
Bill Kim
 
[Algorithm] Heap Sort
[Algorithm] Heap Sort
Bill Kim
 
[Algorithm] Counting Sort
[Algorithm] Counting Sort
Bill Kim
 
[Algorithm] Selection Sort
[Algorithm] Selection Sort
Bill Kim
 
[Algorithm] Merge Sort
[Algorithm] Merge Sort
Bill Kim
 
[Algorithm] Insertion Sort
[Algorithm] Insertion Sort
Bill Kim
 
[Algorithm] Bubble Sort
[Algorithm] Bubble Sort
Bill Kim
 
[Algorithm] Binary Search
[Algorithm] Binary Search
Bill Kim
 
[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)
Bill Kim
 
[Swift] Data Structure - Tree
[Swift] Data Structure - Tree
Bill Kim
 
[Swift] Data Structure Introduction
[Swift] Data Structure Introduction
Bill Kim
 
Design Pattern Introduction
Design Pattern Introduction
Bill Kim
 
[Swift] Visitor
[Swift] Visitor
Bill Kim
 
[Swift] Template Method
[Swift] Template Method
Bill Kim
 
[Swift] State
[Swift] State
Bill Kim
 
[Algorithm] Sorting Comparison
[Algorithm] Sorting Comparison
Bill Kim
 
[Algorithm] Big O Notation
[Algorithm] Big O Notation
Bill Kim
 
[Algorithm] Shell Sort
[Algorithm] Shell Sort
Bill Kim
 
[Algorithm] Radix Sort
[Algorithm] Radix Sort
Bill Kim
 
[Algorithm] Quick Sort
[Algorithm] Quick Sort
Bill Kim
 
[Algorithm] Heap Sort
[Algorithm] Heap Sort
Bill Kim
 
[Algorithm] Counting Sort
[Algorithm] Counting Sort
Bill Kim
 
[Algorithm] Selection Sort
[Algorithm] Selection Sort
Bill Kim
 
[Algorithm] Merge Sort
[Algorithm] Merge Sort
Bill Kim
 
[Algorithm] Insertion Sort
[Algorithm] Insertion Sort
Bill Kim
 
[Algorithm] Bubble Sort
[Algorithm] Bubble Sort
Bill Kim
 
[Algorithm] Binary Search
[Algorithm] Binary Search
Bill Kim
 
[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)
Bill Kim
 
[Swift] Data Structure - Tree
[Swift] Data Structure - Tree
Bill Kim
 
[Swift] Data Structure Introduction
[Swift] Data Structure Introduction
Bill Kim
 
Design Pattern Introduction
Design Pattern Introduction
Bill Kim
 
[Swift] Visitor
[Swift] Visitor
Bill Kim
 
[Swift] Template Method
[Swift] Template Method
Bill Kim
 
[Swift] State
[Swift] State
Bill Kim
 
Ad

[Swift] Data Structure - Linked List

  • 3. Linked List 링크드 리스트(Linked List)는 순차적으로 모인 데이터의 모음으로 서 다음 차례의 노드 주소를 가지고 있는 형태를 가집니다. 가지고 있는 노드의 주소 형태에 따라서 아래의 두 가지 유형을 나 타낼 수 있습니다. Singly Linked List : 다음 노드(Next Node)의 주소만 가지는 리스트 Double Linked List : 다음 노드 및 이전 노드(Previous Node)의 주소를 가지는 리스트 Linked List를 사용하기 위해서는 시작과 끝의 주소를 알아야 하는 데 이를 head와 tail이라 부릅니다.
  • 4. Concept Linked List의 기본 동작 흐름은 아래와 같습니다.
  • 5. Features Linked List의 특징을 살펴보면 아래와 같습니다. - 데이터를 순차적으로 동적 저장합니다. - 데이터 중복 저장을 허용합니다. - 총 길이의 제한이 없습니다. - 특정 노드의 주소를 모르면 직접 접근이 불가합니다.
  • 6. Implementation Swift를 활용하여 Linked List 를 구현해보겠습니다. 우선 필요한 메소드는 아래와 같습니다. - init : 리스트를 초기화하는 함수 - insert : 데이터 입력(마지막 혹은 특정 노드 위치) - remove : 특정 노드 삭제 - removeLast : 마지막 데이터 삭제 - removeAll : 모든 데이터 삭제 - count : 현재 리스트의 크기를 반환 - isEmpty : 현재 리스트의 크기가 비어있는지 체크
  • 7. Implementation 가장 데이터의 기본이 되는 Node 클래스 입니다. 해당 Node 클래스는 모든 데이터 형식을 받을 수 있도록 Generic 형태로 구현이 되어 있습니다. class LinkedListNode<T> { var value: T var next: LinkedListNode? weak var previous: LinkedListNode? public init(value: T) { self.value = value } }
  • 8. Implementation class LinkedList<T> { typealias Node = LinkedListNode<T> private var head: Node? private var tail: Node? public init() { head = nil tail = nil } public var isEmpty: Bool { return head == nil } public var first: Node? { return head } public var last: Node? { return tail } ....
  • 9. Implementation public func node(at index: Int) -> Node? { if index >= 0 { var node = head var i = index while node != nil { if i == 0 { return node } i -= 1 node = node!.next } } return nil } public func insert(_ value: T) { let newNode = Node(value: value) if let tailNode = tail { newNode.previous = tailNode tailNode.next = newNode } else { head = newNode } tail = newNode } ....
  • 10. Implementation public func insert(_ node: Node, at index: Int) { if index == 0, tail == nil { head = node tail = node } else { guard let nodeAtIndex = self.node(at: index) else { print("Index out of bounds.") return } if nodeAtIndex.previous == nil { head = node } node.previous = nodeAtIndex.previous nodeAtIndex.previous?.next = node node.next = nodeAtIndex nodeAtIndex.previous = node } } ....
  • 11. Implementation public func removeAll() { head = nil tail = nil } public func removeLast() -> T { return remove(node: last!) } public func remove(node: Node) -> T { let prev = node.previous let next = node.next if let prev = prev { prev.next = next } else { head = next } next?.previous = prev node.previous = nil node.next = nil return node.value } ....
  • 12. Implementation public func count() -> Int { guard var node = head else { return 0 } var count = 1 while let next = node.next { node = next count += 1 } return count } ....
  • 13. Implementation public var toString : String { var s = "[" var node = head while node != nil { s += "(node!.value)" node = node!.next if node != nil { s += ", " } } return s + "]" } struct LinkedListIterator : IteratorProtocol { let linkedList: LinkedList var current: Node? init(_ linkedList: LinkedList) { self.linkedList = linkedList self.current = linkedList.head } mutating func next() -> Node? { guard let thisCurrent = current else { return nil } current = thisCurrent.next return thisCurrent } } }
  • 14. Implementation extension LinkedList : Sequence { func makeIterator() -> LinkedListIterator { return LinkedListIterator(self) } } // 사용 예시 let list:LinkedList<Int> = LinkedList<Int>() list.insert(1) list.insert(2) list.insert(3) list.insert(4) list.insert(5) // 현재 리스트 카운트 : 5 print(list.count()) for node in list { print(node.value) // 1 // 2 // 3 // 4 // 5 }
  • 15. References [1] 스위프트 : 연결리스트 (1 / 3) : #LinkedList : #DataStructrue : #자료구조: #swift : https://the-brain-of- sic2.tistory.com/14 [2] 스위프트 : 연결리스트 (2 / 3) : #LinkedList : #값 추가하기, push, append : #값 삽입하기,insert: #swift : https://the- brain-of-sic2.tistory.com/15 [3] [Swift 자료구조 ch08] Linked List : https:// kor45cw.tistory.com/244 [4] Swift로 자료구조, 알고리즘 공부하기 (4) - Linked List : https://kor45cw.tistory.com/4 [5] Data Structure) 링크드 리스트(Linked List) in Swift : https://atelier-chez-moi.tistory.com/90
  • 16. References [6] Data Structure (자료구조) : https://opentutorials.org/module/ 1335 [7] Linked List : https://woongsios.tistory.com/49 [8] Data Structure 데이터 구조 : https://m.blog.naver.com/ PostView.nhn? blogId=jdub7138&logNo=220957839382&proxyReferer=https: %2F%2Fwww.google.com%2F [9] C <18>. 연결리스트 (Linked list) – 자료구조(1) : https:// blog.yagom.net/249/ [10] [Data Structure] 자료구조 - 연결 리스트(Linked List) - 단순 연결 리스트(Singly / Linear Linked List) : https://palpit.tistory.com/ 141