Repository navigation
Expand file tree
/
Copy pathlinked_list.py
More file actions
99 lines (84 loc) · 2.61 KB
/
Copy pathlinked_list.py
File metadata and controls
99 lines (84 loc) · 2.61 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
93
94
95
96
97
98
99
class node:
data = None
next_node = None
def __init__(self,data):
self.data = data
def __repr__(self):
return "<Node data: %s>" %self.data
class linked_lists:
def __init__(self):
self.header = None
def isEmpty(self):
return self.header == None
def size(self):
count = 0
current = self.header
while current:
count += 1
current = current.next_node
return count
def add(self,data):
new_node = node(data)
new_node.next_node = self.header
self.header = new_node
def __repr__(self):
linklist = []
current = self.header
while current:
if current == self.header:
linklist.append(f"[Head:{current.data}]")
elif current.next_node == None:
linklist.append(f"[Tail:{current.data}]")
else:
linklist.append(f"{current.data}")
current = current.next_node
return "-> ".join(linklist)
def search(self , id):
current = self.header
while current:
if current.data == id:
return current
else:
current = current.next_node
return None
def insert(self , index, data):
new_node = node(data)
if index == 0:
new_node.next_node = self.header
self.header = new_node
return 1
current = self.header
current_index = 0
while current:
if current_index == index - 1:
new_node.next_node = current.next_node
current.next_node = new_node
return 1
current = current.next_node
current_index += 1
raise IndexError("index out of range")
def deletedata(self, data):
found = False
previous = None
current = self.header
while current and not found:
if current.data == data and current == self.header:
found = True
self.header = current.next_node
elif current.data == data:
found = True
previous.next_node = current.next_node
else:
previous = current
current = current.next_node
return found
def nodeatIndex(self , index):
if index == 0:
return self.header
else:
current = self.header
position = 0
while position < index:
current = current.next_node
position += 1
return current