MCPcopy Index your code
hub / github.com/BeeBombshell/Python-DSA / SinglyLinkedList

Class SinglyLinkedList

DSA/SinglyLinkedList.py:9–118  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

7
8#class for Singly Linked List
9class SinglyLinkedList():
10 #constructor to initialise head and tail of a Singly Linked List. Iniltially set to None
11 def __init__(self):
12 self.head = self.tail = None
13
14 #method to check if the List is empty
15 def isEmpty(self):
16 if (self.head == self.tail == None):
17 return True
18 return False
19
20 #method to count thee no. of nodes in the list
21 def count(self):
22 if self.isEmpty():
23 return 0
24 n = 0
25 temp = self.head
26 while (temp != None):
27 n += 1
28 temp = temp.next
29 return n
30
31 #method to add an element in the front i.e. head
32 def addFront(self, x):
33 new_node = Node(x)
34 if (self.isEmpty()):
35 self.head = self.tail = new_node
36 return
37 new_node.next = self.head
38 self.head = new_node
39
40 #method to add element in the last i.e. tail
41 def addTail(self, x):
42 new_node = Node(x)
43 if (self.isEmpty()):
44 self.head = self.tail = new_node
45 return
46 self.tail.next = new_node
47 self.tail = new_node
48
49 #method to insert an element at a specific position
50 def insert(self, x, pos):
51 if pos == 1:
52 self.addFront(x)
53 return
54 if pos == (self.count()+1):
55 self.addTail(x)
56 return
57 new_node = Node(x)
58 temp = self.head
59 i = 1
60 while (temp != None) and (i < pos-1):
61 temp = temp.next
62 i += 1
63 if (temp == None):
64 return
65 new_node.next = temp.next
66 temp.next = new_node

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected