Skip to content

Instantly share code, notes, and snippets.

@kunthar
Last active August 6, 2020 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kunthar/d3952002c8f37259526715c56a2bd2e9 to your computer and use it in GitHub Desktop.
Save kunthar/d3952002c8f37259526715c56a2bd2e9 to your computer and use it in GitHub Desktop.
Create a linkedlist and remove dups from llist
"""
There is no direct implementation of Linkedlist in Python even in 3. So we have to implement it first.
Please note that we have a collections.deque class but delete operation is nearly the same polynomial time bruh.
To get more detail on this please read here:
https://realpython.com/linked-lists-python/
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.last_node = None
def append(self, data):
if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next
def get_prev_node(self, ref_node):
current = self.head
while (current and current.next != ref_node):
current = current.next
return current
def remove(self, node):
prev_node = self.get_prev_node(node)
if prev_node is None:
self.head = self.head.next
else:
prev_node.next = node.next
def display(self):
current = self.head
while current:
print(current.data, end = ' \n')
current = current.next
def remove_dups(llist):
current1 = llist.head
while current1:
data = current1.data
current2 = current1.next
while current2:
if current2.data == data:
llist.remove(current2)
current2 = current2.next
current1 = current1.next
a_llist = LinkedList()
data_list = input('Insert elements in the linked list with space: ').split()
for data in data_list:
a_llist.append(int(data))
remove_dups(a_llist)
print('The list with dups removed: ')
print('----------------------------\n')
a_llist.display()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment