Remove Nth Node From End of List
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.# 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
"""
dummy = ListNode(0)
dummy.next = head
fast = slow = head
for i in range(0,n):
fast = fast.next
# 判断是不是删除的是头节点
if not fast:
head = head.next
return head
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.nextLast updated