Created
January 7, 2020 10:21
-
-
Save spurscho/6d3f3e23548e36dbe14b96616a9cfea0 to your computer and use it in GitHub Desktop.
19. Remove Nth Node From End of List
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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