Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save spurscho/6d3f3e23548e36dbe14b96616a9cfea0 to your computer and use it in GitHub Desktop.
Save spurscho/6d3f3e23548e36dbe14b96616a9cfea0 to your computer and use it in GitHub Desktop.
19. Remove Nth Node From End of List
/**
* 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 Solution {
func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
var p1 = head
var p2 = p1
var prev = p1
if n == 1 && p1?.next == nil {
return nil
}
for _ in 0 ..< n {
p1 = p1?.next
}
if p1 == nil {
return head?.next
}
while p1 != nil {
p1 = p1?.next
prev = p2
p2 = p2?.next
if p1 == nil {
prev?.next = p2?.next
}
}
return head
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment