
思路
获取链表长度,然后开始遍历,当遍历到 链表长度-n-1时,此时结点的下一个结点即为要删除的结点,所以停止循环,直接删下一个结点 即p.next=p.next.next
需要注意一个特殊情况:删除头结点
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if head is None:
return None
if head.next is None:
return None
p = head
length = 0
while p:
length+=1
p=p.next
length=length-n
p =head
i = 0
while p:
i+=1
if i<length:
p=p.next
else:
break
if length== 0:
#删除头结点
p.val =p.next.val
p.next=p.next.next
else:
p.next =p.next.next
return head
若不需要特别注意删除头结点:
创建一个新链表=[0] +原链表 此时进行上方操作
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if head is None:
return None
if head.next is None:
return None
p = head
length = 0
while p:
length+=1
p=p.next
length=length-n
prelist =ListNode(0)
pre = prelist
pre.next=head
p = prelist
i = 0
while p:
i+=1
if i<=length:
p=p.next
else:
break
p.next=p.next.next
return prelist.next