[python]代码库
class Node:
def __init__(self, data):
self.data = data
self.next = None
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
# Example usage
# Create a linked list: 1 -> 2 -> 3 -> 4 -> None
head = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
head.next = node2
node2.next = node3
node3.next = node4
# Reverse the linked list
reversed_head = reverse_linked_list(head)
# Print the reversed linked list
curr = reversed_head
while curr:
print(curr.data)
curr = curr.next