|
| 1 | +# Single linkedlist |
| 2 | +class Node: |
| 3 | + def __init__(self, data): |
| 4 | + self.data = data # create data or node |
| 5 | + self.next = None # default next is none |
| 6 | + |
| 7 | + |
| 8 | +class Sll: |
| 9 | + def __init__(self): |
| 10 | + self.head = None # Head node is starting node |
| 11 | + |
| 12 | + def traversal(self): |
| 13 | + if self.head is None: |
| 14 | + print("linked list is empty") |
| 15 | + else: |
| 16 | + a = self.head |
| 17 | + while a is not None: |
| 18 | + print(a.data, end=" ") |
| 19 | + a = a.next |
| 20 | + print() |
| 21 | + |
| 22 | + def insert_beginning(self, data): |
| 23 | + print("Insert at the beginning:") |
| 24 | + nb = Node(data) |
| 25 | + nb.next = self.head |
| 26 | + self.head = nb |
| 27 | + |
| 28 | + |
| 29 | +n1 = Node(5) # create a data=5 and pass value in Node class |
| 30 | +sll = Sll() # create a object of sll |
| 31 | +sll.head = n1 # now assign a n1 object to sll.head variable now sll.head=5 |
| 32 | +n2 = Node(10) # and create another data=10 node and pass value in Node class |
| 33 | +n1.next = n2 # now connect the two nodes |
| 34 | +n3 = Node(15) |
| 35 | +n2.next = n3 |
| 36 | +n4 = Node(20) |
| 37 | +n3.next = n4 |
| 38 | +sll.traversal() |
| 39 | +sll.insert_beginning(1) |
| 40 | +sll.traversal() |
| 41 | + |
| 42 | + |
| 43 | +# Output: |
| 44 | +# 5 10 15 20 |
| 45 | + |
| 46 | +# |
| 47 | +# First we pass the 5 data in Node class. n1 have n1.data=5 |
| 48 | +# Then we create the object for Sll default constructor will execute then it sll.head = none. |
| 49 | +# Then we assign the sll.head = n1 which is nothing but n1 so sll.head = n1 |
| 50 | +# Now we create another data for n2 which have Node(10) now n2.data=10 wil assign |
| 51 | +# now we need to connect nodes n1.next = none is default but we are modifing now n1.next = n2 |
| 52 | +# same way we are mapping untill last node |
| 53 | +# we finally mapped how to print it. |
| 54 | +# For that reason in Sll class we create function called tranversal() |
| 55 | +# sll.traversal we are calling at last now it will check sll.head is none or not |
| 56 | +# sll.head is n1 so it will go to else part there we are printing a = self.head we are keeping |
| 57 | +# then we are checking in while a is not none inside while print the a.data |
| 58 | +# then after we are reassigning a = a.next which is n2 again it went to while its not none |
| 59 | +# then n2.data will print then n2.next = n3 now a = n3 |
| 60 | +# it will repeat untill last node. |
0 commit comments