link list

# Node class

class Node:

    def __init__(self, data):   # Correct constructor

        self.data = data

        self.ref = None



# Linked List class

class LinkedList:

    def __init__(self):   # Correct constructor

        self.head = None


    # Insert node at beginning

    def add_begin(self, data):

        new_node = Node(data)

        new_node.ref = self.head

        self.head = new_node


    # Print Linked List

    def print_LL(self):

        if self.head is None:

            print("Linked list is empty")

        else:

            n = self.head

            while n is not None:

                print(n.data, "---->", end="")

                n = n.ref

            print()


    # Search element in Linked List

    def search(self, key):

        n = self.head

        while n is not None:

            if n.data == key:

                return True

            n = n.ref

        return False


    # Delete first node

    def delete_begin(self):

        if self.head is None:

            print("Linked list is empty")

        else:

            self.head = self.head.ref



# ---------------- Driver Code ----------------

LL1 = LinkedList()


LL1.add_begin(40)

LL1.add_begin(30)

LL1.add_begin(20)

LL1.add_begin(10)


print("\n\tDATA INSERTED IN SINGLE LINKED LIST")

LL1.print_LL()


key = 10

if LL1.search(key):

    print("\n" + str(key) + " is found")

else:

    print(str(key) + " is not found")


print("\n Element Present Before Delete Operation \n")

LL1.print_LL()


print("\n Element Present After Delete Operation \n")

LL1.delete_begin()

LL1.print_LL()


LL1.delete_begin()

LL1.print_LL()

Comments

Popular posts from this blog

college

company

company database