查看更多leetcode题目swift解法,前往https://jinblack.com/leetcode-swift/
https://leetcode.com/problems/reverse-linked-list-ii/
The speed is really fast now. But the memory space cost too much. One way to optimize the memory: I think we can change pre
, cur
, to the val
of ListNode
. We just change the value of the reveresed nodes other than change the reference of the nodes. This can reduce the memory usage.
func reverseBetween(_ head: ListNode?, _ m: Int, _ n: Int) -> ListNode? {
guard m != n && head != nil else { return head }
var i = 1
var pre: ListNode?
var cur = head
var first: ListNode?
while let nd = cur, i <= n {
if i < m {
cur = nd.next
if i == m - 1 {
first = nd
}
} else if i == m {
cur = nd.next
pre = nd
} else if m < i && i < n {
cur = nd.next
nd.next = pre
pre = nd
} else if i == n {
if let f = first {
f.next?.next = nd.next
f.next = nd
nd.next = pre
return head
} else {
head?.next = nd.next
nd.next = pre
return nd
}
}
i += 1
}
return head
}
Runtime: 8 ms, faster than 100.00% of Swift online submissions for Reverse Linked List II.
Memory Usage: 18.9 MB, less than 25.00% of Swift online submissions for Reverse Linked List II.