Advertisement
Guest User

Untitled

a guest
Dec 9th, 2019
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.07 KB | None | 0 0
  1. # Python program to reverse a linked list  
  2. # Time Complexity : O(n)
  3. # Space Complexity : O(1)
  4.  
  5. # Node class  
  6. class Node:
  7.  
  8.     # Constructor to initialize the node object
  9.     def __init__(self, data):
  10.         self.data = data
  11.         self.next = None
  12.  
  13. class LinkedList:
  14.  
  15.     # Function to initialize head
  16.     def __init__(self):
  17.         self.head = None
  18.  
  19.     # Function to reverse the linked list
  20.     def reverse(self):
  21.         prev = None
  22.         current = self.head
  23.         while(current is not None):
  24.             next = current.next
  25.             current.next = prev
  26.             prev = current
  27.             current = next
  28.         self.head = prev
  29.          
  30.     # Function to insert a new node at the beginning
  31.     def push(self, new_data):
  32.         new_node = Node(new_data)
  33.         new_node.next = self.head
  34.         self.head = new_node
  35.  
  36.     # Utility function to print the linked LinkedList
  37.     def printList(self):
  38.         temp = self.head
  39.         while(temp):
  40.             print temp.data,
  41.             temp = temp.next
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement