-
Notifications
You must be signed in to change notification settings - Fork 179
Expand file tree
/
Copy pathlinked_list.py
More file actions
64 lines (54 loc) · 1.35 KB
/
Copy pathlinked_list.py
File metadata and controls
64 lines (54 loc) · 1.35 KB
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
class Node:
value = None
next = None
def __init__(self, v):
self.value = v
self.next = None
class LinkedList:
_head = None
def __init__(self, lst=None):
if isinstance(lst, list):
self.list_to_linkedlist(lst)
def __eq__(self, other):
if not isinstance(other, LinkedList):
# don't attempt to compare against unrelated types
return False
if self.length() != other.length():
return False
n = self._head
m = other._head
while n:
if n.value != m.value:
return False
n = n.next
m = m.next
return True
def length(self):
n = self._head
count = 0
while n:
count += 1
n = n.next
def add(self, v):
new = Node(v)
if not self._head:
self._head = new
return
p = self._head
while p.next:
p = p.next
p.next = new
def list_to_linkedlist(self, lst):
for item in lst:
self.add(item)
def print(self):
p = self._head
str_lst = ''
if not p:
print('[]')
while p:
str_lst += '{}->'.format(p.value)
p = p.next
print(str_lst)
def head(self):
return self._head