forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseLinkedList.swift
46 lines (37 loc) · 1.05 KB
/
ReverseLinkedList.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* Question Link: https://leetcode.com/problems/reverse-linked-list/
* Primary idea: Use two helper nodes, traverse the linkedlist and change point direction each time
* Time Complexity: O(n), Space Complexity: O(1)
*
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class ReverseLinkedList {
func reverseList(head: ListNode?) -> ListNode? {
var temp: ListNode?
var first = head
while first != nil {
let second = first!.next
first!.next = temp
temp = first
first = second
}
return temp
}
func reverseList(_ head: ListNode?) -> ListNode? {
guard let h = head, let next = h.next else {
return head
}
let node = reverseList(next)
next.next = h
h.next = nil
return node
}
}