Question of the Day: Reversing a Linked List

Problem-solving ideas:

  1. Define three pointers: prev, curr and next, which represent the previous node, current node and next node of the current node respectively.
  2. Initialize prev as None, and curr as the head node of the linked list.
  3. Traverse the linked list, for each node:
  • Save the node next to the current node as next.
  • Point the pointer of the current node to the previous node prev to complete the inversion of the node.
  • Update prev to current node.
  • Update curr to the next node next.
  1. When the traversal ends, the head node of the linked list becomes the tail node of the original linked list, so the pointer of the tail node of the original linked list points to None.
  2. Returns the head node of the inverted linked list, which is the tail node of the original linked list.
    Code implementation and comments:
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def reverse_linked_list(head):
    prev = None  # 当前节点的前一个节点
    curr = head  # 当前节点
    
    while curr:
        next_node = curr.next  # 当前节点的下一个节点
        
        # 反转指针
        curr.next = prev  # 将当前节点的指针指向前一个节点
        
        # 更新指针位置
        prev = curr  # 更新前一个节点为当前节点
        curr = next_node  # 更新当前节点为下一个节点
    
    return prev  # 返回反转后的链表的头节点

# 测试
# 创建链表 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)

# 反转链表
new_head = reverse_linked_list(head)

# 遍历打印反转后的链表
while new_head:
    print(new_head.val, end=" ")
    new_head = new_head.next
# 输出: 5 4 3 2 1

The time complexity of this algorithm is O(n), where n is the length of the linked list. During the execution of the algorithm, the linked list needs to be traversed once, and the pointer inversion operation is performed on each node. Therefore, the overall time complexity is linear.

Guess you like

Origin blog.csdn.net/qq_29669259/article/details/131592550