美文网首页
leetcode第十九题 —— 删除链表的倒数第N个节点

leetcode第十九题 —— 删除链表的倒数第N个节点

作者: 不分享的知识毫无意义 | 来源:发表于2019-12-26 07:52 被阅读0次

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

相关文章

网友评论

      本文标题:leetcode第十九题 —— 删除链表的倒数第N个节点

      本文链接:https://www.haomeiwen.com/subject/vglfoctx.html