原题 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.
思路: 1. 求出链表的节点个数noden 2. 移除的节点即为noden-n
代码实现
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
""" get the count of node"""
tmp=head
noden=0
while tmp!=None:
noden+=1
tmp=tmp.next
"""position the previous node to delete"""
tmp=head
tmpn=0
if noden==n:
head=head.next
return head
while tmpn<noden-n-1:
tmp=tmp.next
tmpn+=1
tmp.next=tmp.next.next
return head