Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
class Node(object):
    # Constructor
    def __init__(self, data=None, next=None):
        self.data = data
        self.next = next

    # Function to get data
    def get_data(self):
        return self.data

    # Function to get next node
    def get_next(self):
        return self.next

    # Function to set next field
    def set_next(self, new_next):
        self.next = new_next


class LinkedList(object):
    def __init__(self, head=None):
        self.head = head

    # Function to insert data
    def insert(self, data):
        # new_node is a object of class Node
        new_node = Node(data)
        new_node.set_next(self.head)
        self.head = new_node
        print("Node with data " + str(data) + " is created succesfully")

    # Function to get size
    def size(self):
        current = self.head
        count = 0
        while current:
            count += 1
            current = current.get_next()
        print("Size of link list is " + str(count))

    # Function to search a data
    def search(self, data):
        current = self.head
        found = False
        while current and found is False:
            if current.get_data() == data:
                found = True
            else:
                current = current.get_next()
        if current is None:
            print("Node with data " + str(data) + " is not present")
        else:
        	print("Node with data " + str(data) + " is found")


    # Function to delete a node with data
    def delete(self, data):
        current = self.head
        previous = None
        found = False
        while current and found is False:
            if current.get_data() == data:
                found = True
            else:
                previous = current
                current = current.get_next()
        if current is None:
            print("Node with data " + str(data) + " is not in list")
        elif previous is None:
            self.head = current.get_next()
            print("Node with data " + str(data) + " is deleted successfully")
        else:
            previous.set_next(current.get_next())
            print("Node with data " + str(data) + " is deleted successfully")

SLL = LinkedList() # Creates an object of class LinkedList
SLL.size() # prints 'Size of link list is 0'
data_elements = [5, 10, 2, 6, 8, 20]
# prints the entire list
for element in data_elements:
	SLL.insert(element)
SLL.size() # prints 'Size of link list is 6'
SLL.search(4) # prints 'Node with data 4 is not present'
SLL.search(5) # prints 'Node with data 5 is found'
SLL.delete(4) # prints 'Node with data 4 is not in list'
SLL.delete(5) # prints 'Node with data 5 is deleted successfully'