Swift LeetCode 系列之 19: Remove Nth Node From End of List

https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/

  1. 利用快慢指针快速定位到要删除节点的位置
/**
 * 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
    }
}
    原文作者:TimberTang
    原文地址: https://www.jianshu.com/p/c7156a832540
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞