Reverse a linked list in python
To reverse a linked list in Python, you can use an iterative approach with a loop. Here is an example of how you might do this:
# Define a Node class
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
# Define a LinkedList class
class LinkedList:
def __init__(self, head=None):
self.head = head
def reverse(self):
# Set the current and previous nodes
current = self.head
previous = None
# Iterate through the list and reverse the links
while current:
next = current.next
current.next = previous
previous = current
current = next
# Set the head to the last node
self.head = previous
# Test the LinkedList class
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node1.next = node2
node2.next = node3
node3.next = node4
linked_list = LinkedList(node1)
linked_list.reverse()
node = linked_list.head
while node:
print(node.value)
node = node.next
# Output: 4 3 2 1
This approach works by iterating through the linked list and reversing the links between the nodes one at a time. The previous node starts as None and is updated to the current node after the links are reversed. The current node is updated to the next node in the list, and the process repeats until the end of the list is reached.
0 Comments
if you are not getting it then ask i am glad to help