题目描述
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶: 你能尝试使用一趟扫描实现吗?
代码实现
执行用时 :24 ms, 在所有 Python 提交中击败了68.74%的用户
内存消耗 :12.6 MB, 在所有 Python 提交中击败了5.88%的用户
采用先获取需删除节点正数位置,再进行删除的方法。
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
# 获取链表长度
lens = 0
currents = head
while currents is not None:
lens += 1
currents = currents.next
# 获取正数位置
inde = lens-n
previous = head
current = head
if inde==0:
head = head.next
else:
for i in range(inde):
previous = current
current = current.next
previous.next = current.next
return head