def reverseLinkedList(self):
# Complexity Time: O(n), Complexity Memory: O(1)
# Initialize previous and current pointers
prev, curr = None, self.head
# loop over the linked list nodes until the current is Null
while curr:
# Store current's next node in a temporary variable
next = curr.next
# Reverse current node's pointer
curr.next = prev
# Move pointers one position ahead
prev = curr
curr = next
self.head = prev
/*method to reverse a linked list */
reverse(list) {
let current = list.head;
let prev = null;
let next = null;
if (this.head) {
//only one node
if (!this.head.next) { return this; }
while (current) {
next = current.next;//store next node of current before change
current.next = prev;//change next of current by reverse the link
prev = current;//move prev node forward
current = next;//move current node forward
}
list.head = prev
return list
}
return "is empty"
}
/* Before changing next pointer of current node,
store the next node */
next = curr -> next
/* Change next pointer of current node */
/* Actual reversing */
curr -> next = prev
/* Move prev and curr one step ahead */
prev = curr
curr = next
# Python program to reverse a linked list
# Time Complexity : O(n)
# Space Complexity : O(n) as 'next'
#variable is getting created in each loop.
# Node class
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to reverse the linked list
def reverse(self):
prev = None
current = self.head
while(current is not None):
next = current.next
current.next = prev
prev = current
current = next
self.head = prev
# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Utility function to print the LinkedList
def printList(self):
temp = self.head
while(temp):
print (temp.data,end=" ")
temp = temp.next
# Driver program to test above functions
llist = LinkedList()
llist.push(20)
llist.push(4)
llist.push(15)
llist.push(85)
print ("Given Linked List")
llist.printList()
llist.reverse()
print ("
Reversed Linked List")
llist.printList()