Skip to content

Commit a355627

Browse files
committed
solve
1 parent e90ae4f commit a355627

File tree

1 file changed

+26
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)