Skip to content

Commit

Permalink
Create: 19-Remove-Nth-Node-From-End-of-List.swift
Browse files Browse the repository at this point in the history
  • Loading branch information
Ykhan799 authored Sep 19, 2022
1 parent f0c76fb commit 8db7e1e
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions swift/19-Remove-Nth-Node-From-End-of-List.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* 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 removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
if head === nil {
return head
}
var slow = head, fast = head
for i in 1...n + 1 {
if (slow === nil) {
return head?.next
}
slow = slow?.next
}

while slow != nil {
slow = slow?.next
fast = fast?.next
}
fast?.next = fast?.next?.next
return head
}
}

0 comments on commit 8db7e1e

Please sign in to comment.