生活随笔
收集整理的這篇文章主要介紹了
1025 反转链表 (25分)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
輸入樣例:
00100 6 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218
輸出樣例:
00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 6 -1
解題心得:
本題兩個注意點,1??不是所有結點都是在鏈表上;2??反轉后鏈表中每個結點的next仍指向反轉后的下一個結點,一定要審題!第5個測試點超時,python本身的效率是一方面,代碼可能還有優化的空間,但是沒有必要,既然選擇使用python說明對效率要求不是特別高,也可以把python代碼過分優化,就失去了代碼的優雅性。針對pat的題目而言,絕大部分用python沒有問題,對于部分超時問題,請把python代碼用c++或者c翻譯一遍就沒問題;每次做pat提交錯誤時,都是無從下手->然大悟->原來如此->如此簡單。
import sys
from collections
import defaultdict
def get_k_reverse(first_addr
, nodes
, k
):addr
= first_addrsorted_nodes
= []while addr
!= '-1':sorted_nodes
.append
(nodes
[addr
])addr
= nodes
[addr
][2]i
= 0n
= len(sorted_nodes
)loops
= n
// k
while i
< loops
:for j
in reversed(range(i
* k
, (i
+ 1) * k
)):print(' '.join
(sorted_nodes
[j
][0:2]), end
=' ')if j
- 1 >= i
* k
:print(sorted_nodes
[j
- 1][0])elif i
+ 1 < loops
:print(sorted_nodes
[(i
+ 2) * k
- 1][0])elif i
+ 1 == loops
and (i
+ 1) * k
< n
:print(sorted_nodes
[(i
+ 1) * k
][0])else:print('-1')i
+= 1for j
in range(i
* k
, n
):print(' '.join
(sorted_nodes
[j
][0:2]), end
=' ')if j
+ 1 < n
:print(sorted_nodes
[j
+ 1][0])else:print('-1')if __name__
== '__main__':first_addr
, n
, k
= sys
.stdin
.readline
().split
()n
= int(n
)k
= int(k
)nodes
= defaultdict
(list)for i
in range(n
):node
= sys
.stdin
.readline
().split
()nodes
[node
[0]] = nodeget_k_reverse
(first_addr
, nodes
, k
)
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的1025 反转链表 (25分)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。