We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent e90ae4f commit a355627Copy full SHA for a355627
reverse-linked-list/sonjh1217.swift
@@ -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