随笔 - 54  文章 - 0  评论 - 6  阅读 - 18万

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

posted on   Silence_cnblogs  阅读(234)  评论(0)    收藏  举报
< 2025年4月 >
30 31 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 1 2 3
4 5 6 7 8 9 10

点击右上角即可分享
微信分享提示