LeetCode算法題python解法:25. Reverse Nodes in k-Group
阿新 • • 發佈:2018-10-09
value it is lee etc multipl constant elif The itself
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.
Example:
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Note:
- Only constant extra memory is allowed.
- You may not alter the values in the list‘s nodes, only nodes itself may be changed.
題意大概是給定鏈表和一個參數K,每K個節點反轉一次,剩下的節點不夠K個則不反轉。
這個題目對時間復雜度要求比較高,遍歷到列表中通過reverse反轉肯定是超時的,只能在鏈表上直接操作反轉。
代碼如下:
class Solution: def reverseKGroup(self, head, k): if head==None: return head out=[] while True: #遍歷鏈表,將鏈表放到一個list中,方便後續反轉指向的操作 out.append(head) if head.next==None: break head=head.nextif k>len(out): return out[0] st=0 end=k while True: for i in range(st+1,end): #將每K個範圍內的節點指向反轉 out[i].next=out[i-1] if end+k<=len(out): #判斷K範圍內最後一節點的指向,如果還存在下一個K則指向下個K的最後一個值 out[st].next=out[end+k-1] elif st+k>=len(out): #如果沒有下個K則指向None out[st].next=None elif st+k<len(out)<end+k: #如果剩下的數不夠湊齊一個K,則指向剩下列表的第一個數 out[st].next=out[end] st+=k end+=k if len(out) < end: break if len(out)<2: return out[0] return out[k-1]
LeetCode算法題python解法:25. Reverse Nodes in k-Group