Practice

 avatar
shinta0x01
python
10 months ago
2.3 kB
4
Indexable
Never
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class Singly:
    def __init__(self):
        self.head = None

    def insert_beginning(self, data):
        new_node = Node(data)

        if self.head is None:
            self.head = new_node
            return
        else:
            new_node.next = self.head
            self.head = new_node

    def insert_end(self, data):
        new_node = Node(data)
        current = self.head

        if self.head is None:
            self.head = new_node
        else:
            while current.next is not None:
                current = current.next

            current.next = new_node


    def insert_before(self, key, data):
        new_node = Node(data)
        current = self.head

        if current.data == key:
            self.head = new_node
            new_node.next = current
            return

        while current.data != key:
            pre_current = current
            current = current.next
            if current.data != key:
                print(key, 'Key not found')
                return

        pre_current.next = new_node
        new_node.next = current

    def insert_after(self, key, data):
        new_node = Node(data)

        if self.head is None:
            self.head = new_node
            return
        else:
            current = self.head
            while current.data != key:
                post_current = current.next
                current = post_current
                if current.data != key:
                    print('Key not found')
                    return

            post_current = current.next
            current.next = new_node
            new_node.next = post_current



    def display(self):
        current = self.head

        if self.head is None:
            print('\nList is Empty')
        else:

            while current is not None:
                print(current.data, '', end='')
                current = current.next


s = Singly()

s.insert_beginning(10)
s.insert_beginning(9)
s.insert_beginning(8)
s.insert_beginning(2)
s.insert_after(222, 11)
# s.insert_end(1)
# s.insert_before(1, 90)

s.display()
Leave a Comment