删除链表中的倒数第n个元素

示例:

输入链表:1->2->3->4->5 , 2

输出:1->2->3->5

Python解决方案1:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        list_ = [head.val]
        while head.next:
            list_.append(head.next.val)
            head.next = head.next.next
            
        list_.pop(-n)
        if not list_:
            return None
        out_head = ListNode(list_[0])
        first = out_head
        for i in list_[1:]:
            a = ListNode(i)
            first.next = a
            first = first.next
        return out_head

Python解决方案2:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """

        length = 0
        first = ListNode(0)
        first.next = head
        while first.next:
            first.next = first.next.next
            length += 1
            
            
        prev = ListNode(0)
        if length == n:
            prev.next = head.next
        else:
            prev.next = head     
            
        i = 0
        while head.next:
            if i != length - n -1:
                head = head.next
            else:
                if head.next.next:
                    head.next = head.next.next
                    head = head.next
                else:
                    head.next = None
            i += 1
        return prev.next

猜你喜欢

转载自www.cnblogs.com/wenqinchao/p/10606727.html