题目:
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.
我的想法:
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if not head:
return
firstindex = head
secondindex = head
#先让一个指针空转n次
for i in range(n):
firstindex = firstindex.next
#如果这个指针空转完指到None,说明要删除的是原链表的第一个值
if firstindex == None:
return head.next
#其他情况
while(firstindex.next != None):
firstindex = firstindex.next
secondindex = secondindex.next
secondindex.next = secondindex.next.next
return head