-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlinked_list.py
More file actions
98 lines (78 loc) · 2.4 KB
/
linked_list.py
File metadata and controls
98 lines (78 loc) · 2.4 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
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
98
from __future__ import unicode_literals
class Node(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
def __repr__(self):
"""Print representation of node."""
return "{val}".format(val=self.val)
class LinkedList(object):
"""Class for a singly-linked list."""
def __init__(self, iterable=()):
self._current = None
self.head = None
self.length = 0
for val in reversed(iterable):
self.insert(val)
def __repr__(self):
"""Print representation of LinkedList."""
node = self.head
output = ""
for node in self:
output += "{!r}, ".format(node.val)
return "({})".format(output.rstrip(' ,'))
def __len__(self):
return self.length
def __iter__(self):
if self.head is not None:
self._current = self.head
return self
def next(self):
if self._current is None:
raise StopIteration
node = self._current
self._current = self._current.next
return node
def insert(self, val):
"""Insert value at head of LinkedList.
args:
val: the value to add
"""
self.head = Node(val, self.head)
self.length += 1
return None
def pop(self):
"""Pop the first val off the head and return it."""
if self.head is None:
raise IndexError
else:
to_return = self.head
self.head = to_return.next
self.length -= 1
return to_return.val
def size(self):
"""Return current length of LinkedList."""
return len(self)
def search(self, search_val):
"""Return the node containing val if present, else None.
args:
search_val: the value to search by
returns: a node object or None
"""
for node in self:
if node.val == search_val:
return node
else:
return None
def remove(self, search_node):
"""Remove given node from list, return None.
args:
search_node: the node to be removed
"""
for node in self:
if node.next == search_node:
node.next = node.next.next
return None
def display(self):
"""Shows representation of LinkedList."""
return repr(self)