- Notifications
You must be signed in to change notification settings - Fork 152
/
Copy pathlinked_list_data_structure.py
84 lines (71 loc) · 2.36 KB
/
linked_list_data_structure.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
classNode:
def__init__(self, data=None):
self.data=data
self.next_node=None
classLinkedList:
def__init__(self, head=None):
self.head=head
defisEmpty(self):
returnself.head==None
definsert(self, data):
# create a temp node
temp=Node(data=data)
# point new node to head
temp.next_node=self.head
# set the head as new node
self.head=temp
definsert_after(self, prev, data):
ifprevisNone:
raiseValueError("Given node is not found...")
returnprev
# create a temp node
temp=Node(data=data)
# set next node of temp to the next node of previous
temp.next_node=prev.next_node
# set next node of previous to point temp
prev.next_node=temp
defsize(self):
# start with the head
current=self.head
count=0
# loop unless current is not None
whilecurrent:
count+=1
current=current.next_node
returncount
defsearch(self, data):
# start with the head
current=self.head
found=False
# loop unless current is not None
whilecurrentandnotfound:
# if found, change flag and return data
ifcurrent.data==data:
found=True
else:
# change current to next node
current=current.next_node
ifcurrentisNone:
# raise Exception if not found
raiseValueError("Data is not in the list")
returncurrent
defdelete(self, data):
# start with the head
current=self.head
previous=None
found=False
# loop unless current is not None
whilecurrentandnotfound:
# if found, change flag
ifcurrent.getData() ==data:
found=True
else:
previous=current
current=current.next_node
ifcurrentisNone:
# raise Exception if not found
raiseValueError("Data is not in the list")
ifpreviousisNone:
self.head=current.next_node
else:
previous.next_node=current.next_node