LeetCode刷题之19.删除链表的倒数第N个节点
我不知道将去向何方,但我已在路上! |
---|
时光匆匆,虽未曾谋面,却相遇于斯,实在是莫大的缘分,感谢您的到访 ! |
- 题目:
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。 - 示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
-
说明: 给定的n保证是有效的。
-
进阶: 你能尝试使用一趟扫描实现吗?
-
代码:
# 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:
count = 1
a = b = head
while a.next != None:
count += 1
a = a.next
temp = count - n
j = 1
while b.next != None:
if j == temp:
b.next = b.next.next
return head
b = b.next
j += 1
return head.next
# 执行用时 :56 ms, 在所有 Python3 提交中击败了48.23%的用户
# 内存消耗 :13.7 MB, 在所有 Python3 提交中击败了5.53%的用户
- 算法说明:
将a和b指向头指针,用a计算出链表的长度,存储在count中。将“删除倒数第n个节点”转换为“删除顺数第temp个节点”;然后用while循环删除第temp个节点,返回头节点head。如果temp等于0,说明删除的是头节点,则进入while循环后,不执行if条件,循环结束后返回head.next。