-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlinkedlist.py
97 lines (74 loc) · 2.27 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
class Node:
"""Implementation for the Node"""
data = None
next_node = None
def __init__(self, data):
self.data = data
def __repr__(self):
return f"Node: {self.data}"
class LinkedList:
"""Implementation for the LinkedList"""
def __init__(self):
self.head = None
def __repr__(self):
"""Return a string representation of the list."""
nodes = []
current = self.head
while current:
if current is self.head:
nodes.append(f"[Head: {current.data}]")
elif current.next_node is None:
nodes.append(f"[Tail: {current.data}]")
else:
nodes.append(f"[{current.data}]")
current = current.next_node
return '-> '.join(nodes)
def search(self,value):
"""Search the linked list for a node with the requested value and return the node."""
current = self.head
while current:
if current.data == value:
return current
current = current.next_node
return None
def insert(self, data, index):
"""Insert a new node with the given data at the given index."""
if index == 0:
self.add(data)
if index > 0:
new = Node(data)
position = index
current = self.head
while position > 1:
current = Node.next_node
position -= 1
prev_node = current
next_node = current.next_node
prev_node.next_node = new
new.next_node = next_node
def is_empty(self):
"""Return True if the list is empty."""
return self.head == None
def size(self):
"""Return the number of nodes in the list."""
current = self.head
count = 0
while current:
count += 1
current = current.next_node
return count
def add(self,data):
"""Add a new node at the head of the list."""
new_node = Node(data)
new_node.next_node = self.head
self.head = new_node
return self.head
l = LinkedList()
l.add(20)
l.add(10)
l.add(22)
l.add(90)
print(l.size())
print(l)
print(l.search(22))
print(l.search(100))