mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2025-08-04 15:01:35 +00:00
为链表篇 增加 Swift 实现
This commit is contained in:
@@ -225,5 +225,41 @@ class Solution:
|
||||
return dummyNode.next
|
||||
```
|
||||
|
||||
Swift Code:
|
||||
|
||||
|
||||
```swift
|
||||
class Solution {
|
||||
func insertionSortList(_ head: ListNode?) -> ListNode? {
|
||||
if head == nil && head?.next == nil {
|
||||
return head
|
||||
}
|
||||
//哑节点
|
||||
var dummyNode = ListNode(-1)
|
||||
dummyNode.next = head
|
||||
//pre负责指向新元素,last 负责指向新元素的前一元素
|
||||
//判断是否需要执行插入操作
|
||||
var pre = head?.next
|
||||
var last = head
|
||||
while pre != nil {
|
||||
//不需要插入到合适位置,则继续往下移动
|
||||
if last!.val <= pre!.val {
|
||||
pre = pre?.next
|
||||
last = last?.next
|
||||
continue
|
||||
}
|
||||
//开始出发,查找新元素的合适位置
|
||||
var temphead = dummyNode
|
||||
while temphead.next!.val <= pre!.val {
|
||||
temphead = temphead.next!
|
||||
}
|
||||
//此时我们已经找到了合适位置,我们需要进行插入,大家可以画一画
|
||||
last?.next = pre?.next
|
||||
pre?.next = temphead.next
|
||||
temphead.next = pre
|
||||
//继续往下移动
|
||||
pre = last?.next
|
||||
}
|
||||
return dummyNode.next
|
||||
}
|
||||
}
|
||||
```
|
||||
|
Reference in New Issue
Block a user