Swift LeetCode 系列之 19: Remove Nt
- 利用快慢指针快速定位到要删除节点的位置
/**
* 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? {
let result = ListNode(0)
result.next = head
var fast:ListNode? = result
var slow:ListNode? = result
for _ in 0 ..< n {
fast = fast!.next
}
while(fast!.next != nil) {
fast = fast!.next
slow = slow!.next
}
slow!.next = slow!.next!.next
return result.next
}
}
本文标题:Swift LeetCode 系列之 19: Remove Nt
本文链接:https://www.haomeiwen.com/subject/qapbmxtx.html
网友评论