返回
无需GetLength,N步到尾,再N步到结果:单链表倒数第N个节点的值
前端
2023-09-02 21:01:20
前言
在剑指Offer的第15题中,要求在不计算单链表长度的情况下,找到倒数第N个节点的值。本文将介绍一种通过双指针法来解决此问题的思路和具体实现。
正文
双指针法的基本思想是使用两个指针,一个指针从单链表的头部开始遍历,另一个指针从单链表的倒数第N个节点开始遍历。然后,两个指针同时向后遍历,当第一个指针到达单链表的尾部时,第二个指针所指向的节点就是倒数第N个节点。
为了实现这一思路,我们需要以下几个步骤:
- 定义两个指针,分别指向单链表的头部和倒数第N个节点。
- 将倒数第N个节点的指针向前移动N个节点,这样两个指针之间的距离就变成了N个节点。
- 然后,两个指针同时向后遍历,直到第一个指针到达单链表的尾部。
- 当第一个指针到达单链表的尾部时,第二个指针所指向的节点就是倒数第N个节点。
以下是代码实现:
def find_nth_node_from_end(head, n):
"""
Finds the nth node from the end of a singly linked list.
Args:
head: The head of the singly linked list.
n: The index of the node to find.
Returns:
The value of the nth node from the end of the singly linked list.
"""
# Check if the input is valid.
if head is None or n <= 0:
return None
# Initialize two pointers.
p1 = head
p2 = head
# Move p2 pointer to the nth node from the head.
for _ in range(n):
if p2 is None:
return None # The list is shorter than n.
p2 = p2.next
# Move both pointers until p1 reaches the end of the list.
while p1.next is not None:
p1 = p1.next
p2 = p2.next
# Return the value of the nth node from the end.
return p2.val
结语
双指针法是一种非常巧妙的算法,可以解决很多链表问题。在本文中,我们介绍了如何使用双指针法来解决剑指Offer的第15题。希望本文能够帮助读者理解双指针法的思想和实现。