feat: add Swift codes for linked_list article

This commit is contained in:
nuomi1
2023-01-08 20:22:59 +08:00
parent 230c7723d5
commit 7556558704
4 changed files with 173 additions and 3 deletions

View File

@@ -10,6 +10,7 @@ let package = Package(
.executable(name: "space_complexity", targets: ["space_complexity"]),
.executable(name: "leetcode_two_sum", targets: ["leetcode_two_sum"]),
.executable(name: "array", targets: ["array"]),
.executable(name: "linked_list", targets: ["linked_list"]),
],
targets: [
.target(name: "utils", path: "utils"),
@@ -18,5 +19,6 @@ let package = Package(
.executableTarget(name: "space_complexity", dependencies: ["utils"], path: "chapter_computational_complexity", sources: ["space_complexity.swift"]),
.executableTarget(name: "leetcode_two_sum", path: "chapter_computational_complexity", sources: ["leetcode_two_sum.swift"]),
.executableTarget(name: "array", path: "chapter_array_and_linkedlist", sources: ["array.swift"]),
.executableTarget(name: "linked_list", dependencies: ["utils"], path: "chapter_array_and_linkedlist", sources: ["linked_list.swift"]),
]
)

View File

@@ -0,0 +1,91 @@
/**
* File: linked_list.swift
* Created Time: 2023-01-08
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
/* n0 P */
func insert(n0: ListNode, P: ListNode) {
let n1 = n0.next
n0.next = P
P.next = n1
}
/* n0 */
func remove(n0: ListNode) {
if n0.next == nil {
return
}
// n0 -> P -> n1
let P = n0.next
let n1 = P?.next
n0.next = n1
P?.next = nil
}
/* 访 index */
func access(head: ListNode, index: Int) -> ListNode? {
var head: ListNode? = head
for _ in 0 ..< index {
head = head?.next
if head == nil {
return nil
}
}
return head
}
/* target */
func find(head: ListNode, target: Int) -> Int {
var head: ListNode? = head
var index = 0
while head != nil {
if head?.val == target {
return index
}
head = head?.next
index += 1
}
return -1
}
@main
enum LinkedList {
/* Driver Code */
static func main() {
/* */
//
let n0 = ListNode(x: 1)
let n1 = ListNode(x: 3)
let n2 = ListNode(x: 2)
let n3 = ListNode(x: 5)
let n4 = ListNode(x: 4)
//
n0.next = n1
n1.next = n2
n2.next = n3
n3.next = n4
print("初始化的链表为")
PrintUtil.printLinkedList(head: n0)
/* */
insert(n0: n0, P: ListNode(x: 0))
print("插入结点后的链表为")
PrintUtil.printLinkedList(head: n0)
/* */
remove(n0: n0)
print("删除结点后的链表为")
PrintUtil.printLinkedList(head: n0)
/* 访 */
let node = access(head: n0, index: 3)
print("链表中索引 3 处的结点的值 = \(node!.val)")
/* */
let index = find(head: n0, target: 2)
print("链表中值为 2 的结点的索引 = \(index)")
}
}

View File

@@ -15,6 +15,16 @@ public enum PrintUtil {
}
}
public static func printLinkedList(head: ListNode) {
var head: ListNode? = head
var list: [String] = []
while head != nil {
list.append("\(head!.val)")
head = head?.next
}
print(list.joined(separator: " -> "))
}
public static func printTree(root: TreeNode?) {
printTree(root: root, prev: nil, isLeft: false)
}