刷題
Level: Hard
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.
Follow up:
Could you solve the problem in O(1) extra memory space?
You may not alter the values in the list's nodes, only nodes itself may be changed.
題意:
每k個為一組,reverse。
不足則為原樣。
解法:
取出link list的值: 以每k個取出
放進 暫時的list 進行 reverse
Note: 不足的不用 reverse
每做一次 就放入最終的list
最後 list 轉 link list
程式碼
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
dummyNode = ListNode()
dummyNode = head
ansList = []
while head!=None:
cnt = k
tmpList = []
for i in range(cnt):
if head == None:
break
#print(head.val)
tmpList.append(head.val)
head = head.next
if len(tmpList)==cnt:
tmpList.reverse()
#print(tmpList)
#ansList.append(tmpList)
#print(ansList)
for j in tmpList:
#print(j)
ansList.append(j)
print(ansList)
ansNode = dummyNode
for k in ansList:
dummyNode.val = k
dummyNode = dummyNode.next
print(ansNode)
return ansNode
Result
時間 不太行
空間 也需額外的list空間