class Node:
def __init__(self, val):
self.data = val
self.next = None
def init_list(head_ptr):
head_ptr.next = None
ptr = head_ptr
init_data = [82, 76, 83, 53, 74]
for data in init_data:
new_node = Node(data)
new_node.next = None
ptr.next = new_node
ptr = ptr.next
def add_node(head_ptr, value):
while True:
head_ptr = head_ptr.next
if not head_ptr.next:
head_ptr.next = Node(value)
break
def Insert_data_index(head_ptr, index, value):
i = 0
new_node = Node(value)
ptr = head_ptr
if index == 0:
new_node.next = head_ptr.next
head_ptr.next = new_node
else:
while True:
ptr = ptr.next
if (index - 1) == i:
new_node.next = ptr.next
ptr.next = new_node
break
if not ptr.next:
break
i += 1
if index > i:
ptr.next = new_node
def Insert_data_value(head_ptr, loc_value, value):
new_node = Node(value)
flag = False
ptr = head_ptr
if loc_value == head_ptr.next.data:
new_node.next = head_ptr.next
head_ptr.next = new_node
else:
while True:
if ptr.next.data == loc_value:
new_node.next = ptr.next
ptr.next = new_node
flag = False
break
else:
flag = True
ptr = ptr.next
if not ptr.next:
break
if flag:
ptr.next = new_node
def Del_Node_Index(head_ptr, index):
flag = False
i = 0
ptr = head_ptr
if index == 0:
head_ptr.next = head_ptr.next.next
flag = True
else:
while True:
ptr = ptr.next
if not ptr.next:
break
if (index - 1) == i:
ptr.next = ptr.next.next
flag = True
break
i += 1
return flag
def Del_Node_Value(head_ptr, value):
flag = False
ptr = head_ptr.next
if head_ptr.next.data == value:
head_ptr.next = head_ptr.next.next
flag = True
else:
while ptr:
if ptr.next.data == value:
ptr.next = ptr.next.next
flag = True
break
ptr = ptr.next
return flag
def Query_data_index(head_ptr, index):
flag = False
i = 0
ptr = head_ptr.next
while ptr:
if i == index:
flag = True
return ptr.data
ptr = ptr.next
i += 1
if not flag:
return flag == -1
def Query_data_value(head_ptr, value):
flag = False
i = 0
ptr = head_ptr.next
while ptr:
if ptr.data == value:
flag = True
return i
ptr = ptr.next
i += 1
if not flag:
return flag == -1
def Print_all(ptr):
while True:
ptr = ptr.next
if not ptr:
break
print(ptr.data, end="\t")
if __name__ == '__main__':
head = Node(None)
init_list(head)
add_node(head_ptr=head, value=999)
add_node(head_ptr=head, value=99)
Insert_data_index(head, 9, 8848)
Insert_data_value(head, 823, 9992)
Print_all(ptr=head)
print()
Del_Node_Index(head, 5)
Print_all(ptr=head)
Del_Node_Value(head, 9992)
print()
Print_all(ptr=head)
print()
print(Query_data_index(head, 2))
print(Query_data_value(head,99))
|