# 編碼:utf-8
class 節點:
def __init__(self, value):
class LinkList:
def __init__(self, data=[0 ]):
self.head = None
self.init_link_list(data)
) (self, data):
if len(data) == 0:
print("初始化資料為空白")
return
self.head = Node(data[0]) data[1:]:
current.next = Node(index)
目前= 目前.下一個
# 取得目前結點
def get_node(self, index):
if sel return
if index > self.get_length() 或索引 print("節點不存在")
return
current = self.head
i = 0
while i if i == index - 1:
return current
current = current.next
i += 1
# 取得目前元素的值
def get_data (self, 索引):
cur return "節點不存在"
return current.data
# 列印鍊錶
def print_link(self):
if self.is_empty():
目前= self.head
while current.next 不是None:
next
else:
list.append(current.data)
def get_length(self):
if self.is_empty():
count = 0
while current.next 不是None:
數+ else :
count += 1
return count
# 若為空,回傳true
# 若不為空,則回傳false
def is_empty(self):
元素索引
# data 插入的值
def add_after(self, index, data):
current = self.get_node(index)
turn "node is not exist"
current_next = current.next
current.next = Node(data)
current = current.next
current.next = current_next
# 在目前元素前插入一個元素
== 1:
current = self.get_node(index)
.head = Node(data)
self.head.next = current
current = pre.next
pre.next = Node(data)
pre next = current
# 前一個取得目前元素的元素
def get_pre_node(self, index):
("link is empty")
return
if index > self.get_length() or index print("node is not exist")
i = 0
while i pre = pre .next
i += 1
# 移除指定元素,並傳回刪除元素的值
def remove( f.is_empty():
data = self.head. data
self.head = self.head.next
current = self.get_node(index)
if pre_node is None or current is None: ")
pre_node.next = current.next
return current.data
current = self.get_node(index)
if current is None:
return "current node is none"
current.data = data
size = self.get_length()
last_node = self.get_node(size)
test
y = (1,2,3,4)
s = ["a" , "b", "c", "d"]
linkList = LinkList(y)
# linkList.init_link_list(["a", "b", "c", "d"])
# secondary = LinkList( )
# secondary.init_link_list(["x", "y", "z"])
# linkList.add_after(-1, "x")
# linkList.add_after(1, "y") List
#link. init_link_list([])
# linkList.add_before(1,"x")
# linkList.print_link()
# print("item:", linkList.get_data(2))
# print("item:", linkList.get_data(2))
# print("length:," .get_length())
# print("為空", linkList.is_empty())
# print(linkList.get_pre_node(3).data)
# print("刪除節點:",linkList.remove(2))
# linkList.merge(第二)
linkList.print_link()