-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.py
More file actions
72 lines (66 loc) · 2.02 KB
/
Copy pathLinkedList.py
File metadata and controls
72 lines (66 loc) · 2.02 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
class Element():
def __init__(self, value):
self.value = value
self.next = None
class LinkedList():
def __init__(self, head = None):
self.head = head
def append(self, new_element):
current = self.head
if self.head:
while current.next:
current = current.next
current.next = new_element
else:
self.head = new_element
def convertToList(self):
lst = []
current = self.head
if self.head:
lst.append(current.value)
while current.next:
current = current.next
lst.append(current.value)
return lst
def elementAtIndex(self,i):
# Zero-indexed; negative indices not supported
ind = 0
current = self.head
while current:
if i == ind:
return current.value
current = current.next
ind += 1
return None
def insert(self, new_element, i):
# Returns 1 for success, -1 if not possible
if self.head:
if i == 0:
new_element.next = self.head
self.head = new_element
return 1
else:
ind = 0
current = self.head
while current:
if i == ind + 1:
new_element.next = current.next
current.next = new_element
return 1
ind += 1
current = current.next
elif i == 0:
self.head = new_element
return 1
return -1
def deleteFirstOccurrence(self, value):
current = self.head
previous = None
while current.value != value and current.next:
previous = current
current = current.next
if current.value == value:
if previous:
previous.next = current.next
else:
self.head = current.next