删除链表的倒数第N个节点
1.要求
删除链表的倒数第N个节点
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
2.思路及代码
思路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:
cur=head
n1=0
while cur:
n1+=1
cur=cur.next
l=n1-n
if l==0:
head=head.next
return head
cur=head
while l>1:
l-=1
cur=cur.next
cur.next=cur.next.next
return head
思路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:
res = ListNode(0)
res.next = head
l1 = res
l2 = res
for i in range(n):
l1 = l1.next
while l1.next:
l1 = l1.next
l2 = l2.next
l2.next = l2.next.next
return res.next