Advertisement
Guest User

LinkedList

a guest
Jul 1st, 2020
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. # Node class
  2. class Node:
  3.  
  4.     # Function to initialize the node object
  5.     def __init__(self, data):
  6.         self.data = data # Assign data
  7.         self.next = None # Initialize next as null
  8.  
  9. # Linked List class
  10. class LinkedList:
  11.    
  12.     # Function to initialize the Linked List object
  13.     def __init__(self):
  14.         self.head = None
  15.     def print_linkedlist(self):
  16.         nodes = []
  17.         node = self.head
  18.         while node:
  19.             nodes.append(node.data)
  20.             node = node.next
  21.         nodes.append('None')
  22.         print('->'.join(nodes))
  23.  
  24. one = Node("1")
  25. two = Node('2')
  26. three = Node('3')
  27. llist = LinkedList()
  28. llist.head = one
  29. one.next = two
  30. two.next = three
  31.  
  32. def push(self, new_data):
  33.  
  34.     # 1 & 2: Allocate the Node &
  35.     #    Put in the data
  36.     new_node = Node(new_data)
  37.        
  38.     # 3. Make next of new Node as head
  39.     new_node.next = self.head
  40.        
  41.     # 4. Move the head to point to new Node
  42.     self.head = new_node
  43.  
  44. def insertLast(self, new_data):
  45.     #create a new node
  46.     new_node = Node(new_data)
  47.    
  48.     #if linkedlist is empty, make the new node as head
  49.     if self.head is None:
  50.         self.head = new_node
  51.         return
  52.     #else traverse till the last node
  53.     last = self.head
  54.     while (last.next):
  55.         last = last.next
  56.        
  57.     #change the next of last node
  58.     last.next = new_node
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement