链表的介绍
链表(linked_list)是物理存储单元上非连续的、非顺序的存储结构,数据元素的逻辑顺序是通过链表的指针地址实现,每个元素包含两个结点,一个是存储元素的数据域 (内存空间),另一个是指向下一个结点地址的指针域。根据指针的指向,链表能形成不同的结构,例如单链表,双向链表,循环链表等。
链表通过将链点 i 与其邻居链点 i+1 通过指针相关联,从索引 0 到索引 N-1 对链点进行排序。
直接上代码
class Node:
def __init__(self
,data
):
self
.data
= data
self
.next = None
class Linked_listed:
def __init__(self
,head
=None):
self
.head
= Node
(None)
self
.head
.next = None
self
.length
= 0
def Append(self
, new_element
):
current
= self
.head
while current
.next:
current
= current
.next
current
.next = new_element
self
.length
+= 1
def Is_empty(self
):
return self
.length
== 0
def Insert(self
, position
, new_element
):
position
-= 1
if position
< 0 or position
> self
.length
+1:
raise IndexError
('插入时,插入位置不规范!')
temple
= self
.head
for i
in range(0, self
.length
+1):
if position
== i
:
new_element
.next = temple
.next
temple
.next = new_element
else:
temple
= temple
.next
self
.length
+= 1
def Remove(self
, position
):
position
-= 1
if position
< 0 or position
>= self
.length
:
raise IndexError
("删除元素位置索引超出范围")
temple
= self
.head
for i
in range(0, self
.length
):
if position
== i
:
temple
.next = temple
.next.next
else:
temple
= temple
.next
self
.length
-= 1
def Get_length(self
):
return self
.length
def Print(self
):
print("Linked_list:")
temple
= self
.head
while temple
.next != None:
temple
= temple
.next
print(temple
.data
)
def Reserve(self
):
temple
= self
.head
prev
= Node
(None)
prev
.next = None
for i
in range(0,self
.length
):
re_tem
= temple
.next
temple
.next = re_tem
.next
re_tem
.next = None
re_tem
.next = prev
.next
prev
.next = re_tem
self
.head
= prev
def Initlist(self
, data_list
):
temple
= self
.head
self
.length
= len(a
)
for i
in data_list
:
node
= Node
(i
)
node
.next = temple
.next
temple
.next = node
def Change_data(self
,position
,new_element
):
if position
< 0 or position
> self
.length
:
raise IndexError
("Index Error!")
temple
= self
.head
for i
in range(0,self
.length
+1):
if i
== position
:
temple
.data
= new_element
.data
return
else:
temple
= temple
.next
def Search(self
,new_element
):
temple
= self
.head
for i
in range(0,self
.length
+1):
if new_element
.data
== temple
.data
:
print("This Node's index is ",i
)
else:
temple
= temple
.next
if __name__
== '__main__':
a
= [3,2,5,75,45]
b
= Linked_listed
(None)
b
.Initlist
(a
)
b
.Print
()
b
.Reserve
()
b
.Print
()
b
.Change_data
(5,Node
(30))
b
.Print
()
b
.Search
(Node
(30))