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
// Java program for reversing the linked list
class LinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
/* Function to reverse the linked list */
Node reverse(Node node)
{
Node prev = null;
Node current = node;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
node = prev;
return node;
}
// prints content of double linked list
void printList(Node node)
{
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
// Driver Code
public static void main(String[] args)
{
LinkedList list = new LinkedList();
list.head = new Node(85);
list.head.next = new Node(15);
list.head.next.next = new Node(4);
list.head.next.next.next = new Node(20);
System.out.println("Given Linked list");
list.printList(head);
head = list.reverse(head);
System.out.println("");
System.out.println("Reversed linked list ");
list.printList(head);
}
}
// This code has been contributed by Mayank Jaiswal
/*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