class myArray:
def __init__(self, capacity):
self._data = []
self._capacity = capacity
def __getitem__(self, index):
return self._data[index]
def __setitem__(self, index, value):
self._data[index] = value
def __len__(self):
return len(self._data)
def __iter__(self):
for item in self._data:
yield item
def find(self, index):
try:
return self._data[index]
except IndexError:
return None
def delete(self, index):
try:
self._data.pop(index)
return True
except IndexError:
return False
def insert(self, index, value):
if len(self) > self._capacity:
return False
else:
self._data.insert(index, value)
def print_array(self):
for i in self._data:
print(i)
def test():
a = myArray(5)
a.insert(1,2)
a.insert(0,5)
# a.delete(1)
# d = a.__len__()
# e = len(a)
# print(d)
# print(e)
a.print_array()
if __name__ == "__main__":
test()
链表
import pdb
class Node:
def __init__(self, value, next_node=None):
self.value = value
self.next = next_node
def get_data(self):
return self.value
class SinglyLinkList():
def __init__(self):
self._head = None
def find_by_value(self,value):
p = self._head
while p and p.value != value:
p = p.next
return p
def insert_node_to_head(self,node):
if node:
node.next = self._head
self._head = node
def insert_value_to_head(self,value):
new_node = Node(value)
self.insert_node_to_head(new_node)
def insert_node_after(self,node,newnode):
newnode.next = node.next
node.next = newnode
def insert_value_after(self,node,value):
newnode = Node(value)
self.insert_node_after(node,newnode)
def insert_node_before(self,node,newnode):
if self._head == node:
self.insert_node_to_head(newnode)
return
current = self._head
while current.next and current.next != node:
current = current.next
newnode.next = node
current.next = newnode
def insert_value_before(self,node,value):
newnode = Node(value)
self.insert_node_before(node,newnode)
def delete_by_node(self,node):
if node.next:
node.value = node.next.value
node.next = node.next.next
return
# pdb.set_trace()
current = self._head
# node is the last one
while current and current.next != node:
current = current.next
current.next = node.next
def print_all(self):
current = self._head
if current:
print(f"{current.value}",end=" ")
current = current.next
while current:
print(f"{current.value}",end=" ")
current = current.next
if __name__ == "__main__":
l = SinglyLinkList()
l.insert_value_to_head(1)
nodel = l.find_by_value(1)
l.insert_value_after(nodel,3)
l.insert_value_after(nodel,4)
l.insert_value_after(nodel,2)
l.delete_by_node(nodel)
print("----")
l.print_all()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)