Python帶你走進鍊錶的世界

2021-09-25 20:17:04 字數 3234 閱讀 3067

a =[1

,2,3

,4]for i in

range

(len

(a))

:print(id

(a[i]))

if i ==

len(a)-1

:break

print(id

(a[i +1]

)-id(a[i]))

# 下面是最終的執行結果:

"""140722440987280

32140722440987312

32140722440987344

32140722440987376

"""

列表邏輯結構相鄰的元素是指列表索引相鄰的元素,即a[0]與a[1].a[1]與a[2]等等屬於邏輯結構相鄰,然後上面列印了列表相鄰元素的id差值,這個值就是相同的32,也就是說列表邏輯結構上相鄰的元素在實體地址上也是相鄰的.知道了順序儲存結構,那麼鏈式儲存結構的意思就是列表邏輯結構上相鄰的元素在實體地址上是不相鄰的,或者說其相鄰的元素位址是不相關的

# 使用類的方式來實現鍊錶的建立

# 使用類的方式來實現鍊錶的建立

class

node

(object):

def__init__

(self,data =

none

,next

=none):

self.data = data

self.

next

=next

class

createlist

(object):

def__init__

(self)

: self.node = node(

)# 建立鍊錶節點

defhead_insert

(self)

:# 建立頭結點

head_node = node(

) insert_data =

int(

input

('please input the first number:'))

while insert_data !=

9999

: insert_node = node(

) insert_node.data = insert_data

insert_node.

next

= head_node.

next

head_node.

next

= insert_node

insert_data =

int(

input

('please input a new number:'))

print

(head_node.data)

return head_node

# 遍歷列印鍊錶結點

defprint_list

(self,node1 = node())

: node = node1.

next

while node :

print

(node.data)

#列印結點的記憶體位址差值

while node.

next

:print

('id = {}'

.format(id

(node.

next)-

id(node)))

node = node.

next

node = node.

next

# 按值查詢鍊錶結點

deflocate_elem

(self,elem,node1 = node())

: node = node1.

next

count =

1while node !=

none

and node.data != elem:

count +=

1 node = node.

next

if node ==

none

:print

('no matching elem'

)return

return count

# 按位查詢鍊錶結點

defgetelem

(self,num,node1 = node())

: node = node1.

next

count =

0 result =

none

while node !=

none

and count < num:

#考慮等於的情況設定變數初始值

count +=

1 result = node.data

node = node.

next

if node ==

none

:print

('no matching elem'

)return

return result

linked_list = createlist(

)linked_list.node = linked_list.head_insert(

)print

('print the created linkedlist------'

)linked_list.print_list(linked_list.node)

print

(linked_list.node.data)

elem =

1print

('按值elem = 1查詢的結果是------'

)print

(linked_list.locate_elem(elem,linked_list.node)

)num =

2print

('鍊錶中第2個結果是------'

)print

(linked_list.getelem(num,linked_list.node)

)

在上述**中列印了相鄰元素的id差值如下所示:

可以看到其相鄰的id差值並不相等,也就是說其在邏輯結構上相鄰的關係在物理結構上並不相鄰

帶你走進設計模式 內部類的世界

單例模式 保證類只能存在乙個物件 懶漢式 呼叫功能的時候才建立物件 餓漢式 類第一次載入完成之後就建立物件 當多個人同時呼叫靜態方法時,懶漢容易建立不同物件 實現步驟 構造器私有化 私有的靜態的該類的引用 公共的訪問方式 餓漢式 public class single01 public static...

帶你走進ATM的世界實戰篇

atm atm account 賬戶 balancelnquiry 查詢餘額 bankdatabase 銀行資料庫 cashdispenser 取款口 deposit 存款 depositslot 存款口 keypad 鍵盤 screen 螢幕 transaction 交易 withdrawal 取...

具體解釋C 引用 帶你走進引用的世界

一 介紹引用 首先說引用是什麼,大家能夠記住,引用就是乙個別名,比方小王有個綽號叫小狗。他的媽媽喊小狗回家吃飯。那就是在喊小王回家吃飯。接下來我們用兩行 來宣告乙個引用 就拿小王和小狗來說吧 int xiaow int xiaog xiaow 上面就是乙個引用,說明幾點要注意的地方 1.不是取位址符...