leetcode19. 删除链表的倒数第N个节点 python实

2020-02-26  本文已影响0人  vvblack4

题目:

leetcode19题目描述

解法1:

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

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        l = []
        while head:
            l.append(head.val)
            head = head.next

        del l[len(l)-n]        
        if len(l)==0:
            return 

        head = ListNode(l[0])
        r = head
        p = head
        for i in l[1:]:
            node = ListNode(i)  # 新建一个节点
            p.next = node       # 节点连接到当前链表的尾巴上
            p = p.next          # 链表指针向后移动
        return r

解法2:

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

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        count = 0
        p=head
        while p:
            p = p.next
            count +=1

        target = count-n
        if count == n:
            return head.next
        p1 = head
        while target>1:
            p1 = p1.next
            target-=1
        p1.next = p1.next.next
        return head    

解法3:

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

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        slow, fast = head, head
        while n:
            fast= fast.next
            n -= 1

        if fast is None:
            return head.next

        while fast.next:
            slow = slow.next
            fast = fast.next

        slow.next = slow.next.next
        return head

上一篇 下一篇

猜你喜欢

热点阅读