美文网首页Swift LeetCode
Swift LeetCode 系列之 19: Remove Nt

Swift LeetCode 系列之 19: Remove Nt

作者: TimberTang | 来源:发表于2017-11-10 14:50 被阅读45次

    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
        }
    }
    

    相关文章

      网友评论

        本文标题:Swift LeetCode 系列之 19: Remove Nt

        本文链接:https://www.haomeiwen.com/subject/qapbmxtx.html