-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkedList.py
53 lines (44 loc) · 1.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
# Sample linked list class to use with questions
from random import randint
class Node:
def __init__(self, value=None):
self.value = value
self.next = None
self.prev = None
def __str__(self):
return str(self.value)
class LinkedList:
def __init__(self, values = None):
self.head = None
self.tail = None
def __iter__(self):
currentNode = self.head
while currentNode:
# makes a list of nodes
yield currentNode
currentNode = currentNode.next
def __str__(self):
values = [str(x.value) for x in self]
return '->'.join(values)
def __len__(self):
result = 0
node= self.head
while node:
result += 1
node = node.next
return result
def add(self, value):
if self.head is None:
newNode = Node(value)
self.head = newNode
self.tail = newNode
else:
self.tail.next = Node(value)
self.tail = self.tail.next
return self.tail
def generate(self, n, min_value, max_value):
self.head = None
self.tail = None
for i in range(n):
self.add(randint(min_value, max_value))
return self