题目描述
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
代码示例
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
"""
Reverse a singly-linked list.
Parameters:
- head: The head of the linked list.
Returns:
- The head of the reversed linked list.
"""
pre = None # Initialize the previous node as None
cur = head # Start traversal from the head of the linked list
while cur:
tmp = cur.next # Temporary variable to store the next node
cur.next = pre # Reverse the link direction
pre = cur # Move the previous pointer to the current node
cur = tmp # Move the current pointer to the next node
return pre # Return the new head of the reversed linked list
# Create a sample linked list: 1 -> 2 -> 3 -> 4 -> 5
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
# Create an instance of the Solution class
solution = Solution()
# Reverse the linked list
reversed_head = solution.reverseList(head)
# Print the reversed linked list values
while reversed_head:
print(reversed_head.val, end=" ")
reversed_head = reversed_head.next
# Output: 5 4 3 2 1
总结
面对链表反转的问题,最直观的思路就是从链表的头节点开始,遍历每个节点,调换它们之间的链接方向,直到找到链表的末尾节点。我们将末尾节点作为新链表的头节点,这样就完成了链表的反转。 阅读完整个代码随想录后,我发现使用双指针的方式更加简洁和直观。通过一个循环,不仅实现了链表的反转,而且避免了繁琐的节点操作,提高了代码的可读性。