-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkedlist.py
75 lines (65 loc) · 1.7 KB
/
linkedlist.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
class Node:
def __init__(self, val=None, next_node=None):
self.val = val
self.next = next_node
class LinkedList:
def __init__(self):
self.head = None
def insert_at_beginning(self, data):
node = Node(data, self.head)
self.head = node
def insert_at_end(self, data):
if self.head is None:
self.insert_at_end(data)
return
itr = self.head
while itr.next:
itr = itr.next
itr.next = Node(data, None)
def get_length(self):
count = 0
itr = self.head
while itr:
count += 1
itr = itr.next
return count
def insert_at_position(self, position, data):
if self.head is None:
self.insert_at_beginning(data)
return
itr = self.head
i = 0
while itr.next:
if i == position - 1:
itr.next = Node(data, itr.next)
break
itr = itr.next
i += 1
def remove_at(self, position):
if self.head:
return
itr = self.head
i = 0
while itr:
if i == position - 1:
itr.next = itr.next.next
break
itr = itr.next
i += 1
def print_list(self):
if self.head is None:
return "Linked List is empty"
itr = self.head
listr = ''
while itr:
listr += str(itr.val) + '--->'
itr = itr.next
return listr
l = LinkedList()
l.insert_at_beginning(3)
l.insert_at_beginning(1)
l.insert_at_end(5)
print(l.get_lenght())
l.insert_at_position(1, 2)
l.remove_at(2)
print(l.print_list())