Skip to content

Instantly share code, notes, and snippets.

@aliifam
Created March 14, 2022 02:50
Show Gist options
  • Select an option

  • Save aliifam/b9ba4705ddf9962eaa8210f978c89634 to your computer and use it in GitHub Desktop.

Select an option

Save aliifam/b9ba4705ddf9962eaa8210f978c89634 to your computer and use it in GitHub Desktop.
implementation of Single Linked List data structure with python 3
class Node:
def __init__(self, nim=None, nl=None, np=None):
self.nim = nim
self.nl = nl
self.np = np
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.count = 0 #gak wajib cuma buat hitung panjang LL
def addTail(self, nim, nl, np):
databaru = Node(nim, nl, np)
if self.head == None:
self.head = databaru
self.tail = databaru
else:
self.tail.next = databaru
self.tail = databaru
def addHead(self, nim, nl, np):
databaru = Node(nim, nl, np)
if self.head == None:
self.head = databaru
self.tail = databaru
else:
databaru.next = self.head
self.head = databaru
def removeHead(self):
if self.head == None:
print("error, data kosong gak bisa di remove!")
elif self.head.next == None:
self.head = None
self.tail = None
else:
self.head = self.head.next
def removeTail(self):
if self.head == None:
print("error, data kosong gak bisa di remove!")
elif self.head.next == None:
self.head = None
self.tail = None
else:
second_last = self.head
while second_last.next.next:
second_last = second_last.next
second_last.next = None
def display(self):
p = self.head
while p is not None:
print("NIM =", p.nim)
print("Nama Lengkap =", p.nl)
print("Nama Panggilan =", p.np)
print("-------------------------------------------")
p = p.next
def banyakdata(self):
total = 0
p = self.head
while p is not None:
total += 1
p = p.next
return total
LL = LinkedList() #membuat objek linkedlist
LL.addTail(12345, "Aliif Arief Maulana", "Aliif")
LL.addTail(67890, "Baqeer Andhika Maulana", "Baqeer")
LL.display()
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
LL.addHead(54321, "John Rifqi", "jon")
LL.display()
print(LL.banyakdata())
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
LL.removeHead()
LL.display()
print(LL.banyakdata())
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
LL.removeTail()
LL.display()
print(LL.banyakdata())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment