python鍊錶

2021-10-11 03:09:31 字數 2115 閱讀 5727

class

node

: def __init__

(self,data)

: # 要存的資料

self.data = data

# 指向下乙個節點的指標

self.next = none

class

linkedlist

: def __init__

(self)

: # 鍊錶長度

self.size =

0 # 鍊錶的頭部

self.head = none

# 鍊錶的尾部

self.last = none

# index為取鍊錶的第幾節點

def get

(self,index)

:if index<

0 or index>self.size:

raise exception

('超出鍊錶節點範圍'

) # 這裡宣告乙個變數p為當前指標位置,如果鍊錶不為空,

# 則self.head 為第乙個節點位置,它是乙個例項化的node,

# 它的next屬性也一定存過下個節點是誰,

# 依次找下去,找到對應節點位置,返回的是對應index的節點,也是個例項化的node

p = self.head

for i in range

(index)

: p = p.next

return p

def insert

(self,data,index)

: #print

(self.size,index)

if index <

0 or index > self.size:

raise exception

('超出鍊錶節點範圍'

) #宣告乙個節點

node =

node

(data)

#長度為零則為空鍊錶

if self.size ==0:

self.head = node

self.last = node

elif index==0:

# 之前的頭部為新節點的指向

node.next = self.head

# 新節點變為頭部節點

self.head = node

elif self.size == index:

# 最後乙個節點指向新節點

self.last.next = node

# 新節點記錄為最後乙個節點

self.last = node

else

: # 定位插入位置的上乙個節點

prev_node = self.

get(index-1)

# 插入的節點的指向改為上乙個節點的指向

node.next = prev_node.next

# 上個節點的指向改為新插入的節點

prev_node.next = node

self.size+=

1 def output

(self)

: p = self.head

while p is not none:

print

(p.data)

p = p.next

linkedlist =

linkedlist()

# linkedlist.

insert(4

,4)linkedlist.

insert(6

,0)linkedlist.

insert(7

,0)linkedlist.

insert(9

,2)linkedlist.

insert(5

,3)linkedlist.

insert(6

,2)print

(linkedlist.

get(3)

)linkedlist.

output

()

鍊錶(python)

class node def init self,value none next none self.value value self.next next class linkedlist def init self self.head node self.tail none self.length...

python 鍊錶

在c c 中,通常採用 指標 結構體 來實現鍊錶 而在python中,則可以採用 引用 類 來實現鍊錶。節點類 class node def init self,data self.data data self.next none 鍊錶類 class linkedlist def init self...

python鍊錶 鍊錶重新排序

輸入 1 2 3 4 5 6 7 輸出 1 7 2 6 3 5 4 或者輸入 1 2 3 4 5 6 輸出 1 6 2 5 3 4 思路 1.將1 2 3 4 5 6 7分成 1 2 3 與 4 5 6 7,將後半部分逆序7 6 5 4 2.合併1 2 3與7 6 5 4 為1 7 2 6 3 5 ...