Repository navigation
Expand file tree
/
Copy pathlinked_list.py
More file actions
92 lines (73 loc) · 2.58 KB
/
Copy pathlinked_list.py
File metadata and controls
92 lines (73 loc) · 2.58 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
"""
linked_list.py
A basic linked list implementation.
Linked List Overview:
----------------------
Data is stored in an 'Element' or 'Node'.
An element also contains a reference (link) to the next element in
the list, hence the name 'linked list'.
The main benefit of a linked list is that elements can be inserted
or removed very quickly, as these operations only require modifying
a reference. The main drawback is that there is no random access, so
accessing a particular element requires traversing the list from
the beginning.
Many augmented forms of linked lists exist, but this particular
implementation is the most basic (singly linked list).
Time complexity:
----------------
Indexing: O(n)
Insert/delete at beginning: O(1)
Insert/delete at end: O(1) if tail reference is kept, O(n) otherwise
Insert/delete in middle: O(n)
Wiki: http:://en.wikipedia.org/wiki/Linked_list
"""
class NoSuchElementError(Exception):
pass
class Element(object):
def __init__(self, value, next):
self.value = value
self.next = next
class LinkedList(object):
def __init__(self):
self.head = None
self.tail = None
def __iter__(self):
current = self.head
while current != None:
yield(current.value)
current = current.next
def insert_front(self, element):
self.head = Element(element, self.head)
if self.tail == None:
self.tail = self.head
def insert_back(self, element):
if self.empty():
self.insert_front(element)
else:
self.tail.next = self.tail = Element(element, None)
def insert_after(self, existing, element):
existing_node = self.find(existing)
if existing_node == None:
raise NoSuchElementError
existing_node.next = Element(element, existing_node.next)
def delete(self, element):
node = self.head
previous = None
while node != None and node.value != element:
previous = node
node = node.next
if node == None:
raise NoSuchElementError
if node == self.tail:
self.tail = previous
if node == self.head:
self.head = node.next
else:
previous.next = node.next
def find(self, element):
current = self.head
while current != None and current.value != element:
current = current.next
return current
def empty(self):
return self.head == None