mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
添加 206.反转链表 Swift版本
This commit is contained in:
@ -334,6 +334,43 @@ fun reverseList(head: ListNode?): ListNode? {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Swift:
|
||||||
|
```swift
|
||||||
|
/// 双指针法 (迭代)
|
||||||
|
/// - Parameter head: 头结点
|
||||||
|
/// - Returns: 翻转后的链表头结点
|
||||||
|
func reverseList(_ head: ListNode?) -> ListNode? {
|
||||||
|
if head == nil || head?.next == nil {
|
||||||
|
return head
|
||||||
|
}
|
||||||
|
var pre: ListNode? = nil
|
||||||
|
var cur: ListNode? = head
|
||||||
|
var temp: ListNode? = nil
|
||||||
|
while cur != nil {
|
||||||
|
temp = cur?.next
|
||||||
|
cur?.next = pre
|
||||||
|
pre = cur
|
||||||
|
cur = temp
|
||||||
|
}
|
||||||
|
return pre
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 递归
|
||||||
|
/// - Parameter head: 头结点
|
||||||
|
/// - Returns: 翻转后的链表头结点
|
||||||
|
func reverseList2(_ head: ListNode?) -> ListNode? {
|
||||||
|
return reverse(pre: nil, cur: head)
|
||||||
|
}
|
||||||
|
func reverse(pre: ListNode?, cur: ListNode?) -> ListNode? {
|
||||||
|
if cur == nil {
|
||||||
|
return pre
|
||||||
|
}
|
||||||
|
let temp: ListNode? = cur?.next
|
||||||
|
cur?.next = pre
|
||||||
|
return reverse(pre: cur, cur: temp)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||||
|
Reference in New Issue
Block a user