-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnode.py
68 lines (55 loc) · 1.57 KB
/
node.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
class Node(object):
"""Represents a singly linked node."""
def __init__(self, data, next = None):
"""Instantiates a Node with a default next of None."""
self.data = data
self.next = next
def travelsal(head):
probe = head
while probe.next != None:
probe = probe.next
def search(head, targetItem):
probe = head
while probe.next != None and targetItem != probe.data:
probe = probe.next
if probe != None:
return probe
else:
return None
def replaceTargetNode(head, targetItem, newItem):
probe = head
while probe.next != None and targetItem != probe.data:
probe = probe.next
if probe != None:
probe.data = newItem
return True
else:
return False
def replaceIndexNode(head, index, newItem):
probe = head
while index > 0:
probe = probe.next
index -= 1
probe.data = newItem
def insert(head, index, newItem):
if head is None or index <= 0:
head = Node(newItem, head)
else:
probe = head
while index > 1 and probe.next != None:
probe = probe.next
index -= 1
probe.next = Node(newItem, probe.next)
def remove(head, index):
if index <= 0 or head.next is None:
removeItem = head.data
head = head.next
return removeItem
else:
probe = head
while index > 1 and probe.next != None:
probe = probe.next
index -= 1
removeItem = probe.next.data
probe.next = probe.next.next
return removeItem