1.题目
原题
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
例子
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
2.解析
链表构造
3.python代码
class Solution:
def removeNthFromEnd(self, head, n):
headnew = ListNode(0)
l = headnew
headcopy = head
length = 0
i = 0
while headcopy:
headcopy = headcopy.next
length += 1
# print(length)
while head:
if i != length-n:
l.next = ListNode(head.val)
# print('l.val', l.val)
# print('head.val', head.val)
head = head.next
l = l.next
i += 1
else:
# print(head.val)
# print(head.next.val)
l.next = head.next
l = l.next
break
return headnew.next