Skip to content

Commit 90788e4

Browse files
authored
feat: add swift implementation to lcof2 problem: No.024 (#3012)
1 parent 5eb8c94 commit 90788e4

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

lcof2/剑指 Offer II 024. 反转链表/README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,38 @@ public class Solution {
219219
}
220220
```
221221

222+
#### Swift
223+
224+
```swift
225+
/**
226+
* Definition for singly-linked list.
227+
* public class ListNode {
228+
* public var val: Int
229+
* public var next: ListNode?
230+
* public init(_ val: Int) {
231+
* self.val = val
232+
* self.next = nil
233+
* }
234+
* }
235+
*/
236+
237+
class Solution {
238+
func reverseList(_ head: ListNode?) -> ListNode? {
239+
var prev: ListNode? = nil
240+
var current = head
241+
242+
while current != nil {
243+
let next = current?.next
244+
current?.next = prev
245+
prev = current
246+
current = next
247+
}
248+
249+
return prev
250+
}
251+
}
252+
```
253+
222254
<!-- tabs:end -->
223255

224256
<!-- solution:end -->
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* public var val: Int
5+
* public var next: ListNode?
6+
* public init(_ val: Int) {
7+
* self.val = val
8+
* self.next = nil
9+
* }
10+
* }
11+
*/
12+
13+
class Solution {
14+
func reverseList(_ head: ListNode?) -> ListNode? {
15+
var prev: ListNode? = nil
16+
var current = head
17+
18+
while current != nil {
19+
let next = current?.next
20+
current?.next = prev
21+
prev = current
22+
current = next
23+
}
24+
25+
return prev
26+
}
27+
}

0 commit comments

Comments
 (0)