-
Notifications
You must be signed in to change notification settings - Fork 0
/
linked_list.py
71 lines (60 loc) · 1.86 KB
/
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
# This is a python Linked List
class Node(object):
def __init__(self, val, _next=None):
self.val = val
self._next = _next
class LinkedList(object):
def __init__(self, first=None):
self.first = first
def insert(self, new):
# insert new at beginning of list
if not self.first:
self.first = new
else:
new._next = self.first
self.first = new
def pop(self):
# pops first item from list and returns it
if self.size() == 0:
return "THE LIST! IT'S EMPTY!!"
else:
chopped = self.first
self.first = self.first._next
return chopped.val
def size(self):
# returns length of list
current = self.first
size = 0
while current is not None:
size += 1
current = current._next
return size
def search(self, val):
# return node containing 'val' in list, if present (else None)
current = self.first
while current.val != val:
if current._next is None:
return None
else:
current = current._next
return current
def remove(self, node):
# remove node from list, wherever it might be
if self.size() == 0:
return "THE LIST! IT'S EMPTY!!"
else:
previous = None
current = self.first
found = False
while not found:
if current == node:
found = True
elif current is None:
raise ValueError()
else:
previous = current
current = current._next
if previous is None:
self.first = current._next
else:
previous._next = current._next