[英]Understanding Implementation of A Singly-Linked Queue Function
一旦以列表的形式可視化了紙上的單鏈接列表,您會注意到,在每次迭代中,它所做的只是還原連接:
initial setup:
(1) -> (2) -> (3) -> (4) -> (5) -> nil
p q
step 1:
(1) <- (2) -> (3) -> (4) -> (5) -> nil
p q
step 2:
(1) <- (2) <- (3) -> (4) -> (5) -> nil
p q
step 3:
(1) <- (2) <- (3) <- (4) -> (5) -> nil
p q
step 4:
(1) <- (2) <- (3) <- (4) <- (5) nil
p q
這里,
q.next = p
表示“反向連接”; p, q = q, q.next
意味着“向前推進一個節點”。 多次賦值就像一次賦值一樣,但是一次完成-您可以一次提供一個值元組,並一次分配一個等長的值元組:
a, b, c = 1, 2, 3
a == 1 # True
b == 2 # True
c == 3 # True
所以,這是函數的作用:
def reverse(self):
p, q = self.head, self.head.next # initialize p and q as first two elements of queue
while q: # iterate until q is None (that is, until we reach the end of the list)
# This indicates that we will need to have a way for q to advance
# towards the end of the list. Presumably we'll be setting q as
# something that will eventually be None.
# We know that the `next` of the last element in the list will be
# None, so that's a good starting point.
_____________________ # blank line to fill in
self.head, self.tail = self.tail, self.head # swap head and tail of list with each other
self.tail.next = None # set the next element of the tail to None, as it should be.
那么,什么是空白? 好了,我們可以弄清楚每個單獨的變量需要更改為什么。 我們將采用的方法是更改遇到的每個元素的方向 -代替.next
指向下一個元素,我們將其指向上一個元素。 因此,我們想要
q.next = p
因為q
是列表中的第二個元素,而p
是它前面的元素。 然后,我們只想將p
和q
推進到列表中的下兩個元素:
p = q
q = q.next
通常,如果我們在單獨的語句中執行這些操作,則需要一個臨時變量來存儲q.next
的值-但是通過多次賦值,我們可以繞開該變量:
q.next, p, q = p, q, q.next
在過程的最后,扭轉了元素之間的所有聯系 ,我們只是扭轉了頭和尾。 並將self.tail.next
設置為None
,因為self.tail
是曾經是self.head
的元素,我們最初跳過了它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.