Skip to content

Commit

Permalink
Create: 206-Reverse-Linked-List.swift
Browse files Browse the repository at this point in the history
  • Loading branch information
Ykhan799 authored Sep 19, 2022
1 parent 7b8b183 commit f0c76fb
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions swift/206-Reverse-Linked-List.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* 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 === nil || head?.next === nil) {
return head
}

var prev: ListNode? = nil
var curr = head, next = curr?.next

while curr != nil {
next = curr?.next
curr?.next = prev
prev = curr
curr = next
}
return prev
}
}

0 comments on commit f0c76fb

Please sign in to comment.