/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init() { self.val = 0; self.next = nil; }
* public init(_ val: Int) { self.val = val; self.next = nil; }
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
* }
*/
class Solution {
func reverseList(_ head: ListNode?) -> ListNode? {
if head?.next == nil {
return head
}
let p = reverseList(head?.next)
head?.next?.next = head
head?.next = nil
return p
}
}
반복문 버전
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init() { self.val = 0; self.next = nil; }
* public init(_ val: Int) { self.val = val; self.next = nil; }
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
* }
*/
class Solution {
func reverseList(_ head: ListNode?) -> ListNode? {
var stack = [ListNode]()
var cur = head
while cur != nil {
stack.append(cur!)
cur = cur!.next
}
let start = ListNode(0)
cur = start
while !stack.isEmpty {
let top = stack.removeLast()
top.next = nil
cur!.next = top
cur = top
}
return start.next
}
}