-
Notifications
You must be signed in to change notification settings - Fork 0
/
singly_linked_list.py
77 lines (63 loc) · 1.73 KB
/
singly_linked_list.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
from node import Node
class SinglyLinkedList:
def __init__(self):
self.head = None
def push(self, data):
self.head = Node(data, self.head)
def insert_at_index(self, index: int, data):
temp = self.head
if not index:
self.push(data)
return
i = 1
while index > i:
temp = temp.next_node
i += 1
new_node = Node(data, temp.next_node)
temp.next_node = new_node
def append(self, data):
temp = self.head
while temp.next_node:
temp = temp.next_node
temp.next_node = Node(data)
def delete_node(self, index: int):
if not index:
self.head = self.head.next_node
return
i = 1
temp = self.head
while index > i:
temp = temp.next_node
i += 1
node_to_del = temp.next_node
next_node = node_to_del.next_node
temp.next_node = next_node
def print_reverse(self, head):
if not head:
return
self.print_reverse(head.next_node)
print(head.val, end=' ')
def reverse(self):
head = self.head
prev = None
while head:
next_node = head.next_node
head.next_node = prev
prev = head
head = next_node
self.head = prev
def __len__(self) -> int:
if not self.head:
return 0
i = 1
temp = self.head
while temp.next_node:
temp = temp.next_node
i += 1
return i
def print_list(self):
temp = self.head
while temp:
print(temp.val, end=" -> ")
temp = temp.next_node
print('NULL')