LeetCode #19 Remove Nth Node From End of List

LeetCode #19 Remove Nth Node From End of List

Question

Given a linked list, remove the nth node from the end of list and return its head.

For example,

Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

Solution

Approach #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? {
        var t = ListNode(0)
        t.next = head
        var h: ListNode? = t
        var l: ListNode? = t
        for _ in 0..<n {
            l = l?.next
        }
        while l?.next != nil {
            h = h?.next
            l = l?.next
        }
        h?.next = h?.next?.next
        return t.next
    }
}

Time complexity: O(L). L is the length of list.

Space complexity: O(1).

转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/6907667.html

原文地址:https://www.cnblogs.com/silence-cnblogs/p/6907667.html