Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Node class
- class Node:
- # Function to initialize the node object
- def __init__(self, data):
- self.data = data # Assign data
- self.next = None # Initialize next as null
- # Linked List class
- class LinkedList:
- # Function to initialize the Linked List object
- def __init__(self):
- self.head = None
- def print_linkedlist(self):
- nodes = []
- node = self.head
- while node:
- nodes.append(node.data)
- node = node.next
- nodes.append('None')
- print('->'.join(nodes))
- one = Node("1")
- two = Node('2')
- three = Node('3')
- llist = LinkedList()
- llist.head = one
- one.next = two
- two.next = three
- def push(self, new_data):
- # 1 & 2: Allocate the Node &
- # Put in the data
- new_node = Node(new_data)
- # 3. Make next of new Node as head
- new_node.next = self.head
- # 4. Move the head to point to new Node
- self.head = new_node
- def insertLast(self, new_data):
- #create a new node
- new_node = Node(new_data)
- #if linkedlist is empty, make the new node as head
- if self.head is None:
- self.head = new_node
- return
- #else traverse till the last node
- last = self.head
- while (last.next):
- last = last.next
- #change the next of last node
- last.next = new_node
- def del_node(self, data_to_del):
- #store head node
- node = self.head
- #if head node itself hold the key to be deleted
- if node is not None:
- if node.data== data_to_del:
- self.head = node.next
- node = None
- return
- # search for the data to be deleted, keep track of
- # the prev_node as we need to change 'prev.next'
- while node is not None:
- if node.data ==data_to_del:
- break
- prev_node = node
- node = node.next
- #if key was not present in Linked list
- if node == None:
- return
- #unlink the node from linked list
- prev_node.next = node.next
- node = None
Add Comment
Please, Sign In to add comment