問題描述:
給你一個鏈表,每 k 個節點一組進行翻轉,請你返回翻轉后的鏈表。
k 是一個正整數,它的值小於或等於鏈表的長度。
如果節點總數不是 k 的整數倍,那么請將最后剩余的節點保持原有順序。
示例 :
給定這個鏈表:1->2->3->4->5
當 k = 2 時,應當返回: 2->1->4->3->5
當 k = 3 時,應當返回: 3->2->1->4->5
說明 :
你的算法只能使用常數的額外空間。
你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。
方法一:利用棧(不過空間復雜度為O(k))
過程:
一次循環之后:
第二次循環過后:
第三次循環:由於tmp==None,此時count=,因此直接將p.next指向head。最后返回newhead.next即可。
代碼:
class ListNode: def __init__(self,x): self.val=x self.next=None n1=ListNode(1) n2=ListNode(2) n3=ListNode(3) n4=ListNode(4) n5=ListNode(5) n6=ListNode(6) n7=ListNode(7) n1.next=n2;n2.next=n3;n3.next=n4;n4.next=n5 def printListNode(head): while head != None: print(head.val) head=head.next #printListNode(n1) class Solution: def reverseKGroup(self, head,k): newhead = ListNode(0) p = newhead while True: count = k stack = [] tmp = head while count and tmp: stack.append(tmp) tmp = tmp.next count -= 1 if count : p.next = head break while stack: p.next = stack.pop() p = p.next head = tmp return newhead.next s=Solution() t=s.reverseKGroup(n1,2) printListNode(t)
方法二:尾插法
初始化:
進入第一次循環:
進入第二次循環:
依次類推。
再比如:[1,2,3,4,5,6,7],k=3,過程也就是:
[2,3,1,4,5,6,7]
[3,2,1,4,5,6,7]
[3,2,1,5,6,4,7]
[3,2,1,6,5,4,7]
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: newhead= ListNode(0) newhead.next = head pre = newhead tail = newhead while True: count = k while count and tail: count -= 1 tail = tail.next if not tail: break head = pre.next while pre.next != tail: cur = pre.next # 獲取下一個元素 # pre與cur.next連接起來,此時cur(孤單)掉了出來 pre.next = cur.next cur.next = tail.next # 和剩余的鏈表連接起來 tail.next = cur #插在tail后面 # 改變 pre tail 的值 pre = head tail = head return newhead.next
方法三:遞歸,理解不了
class Solution: def reverseKGroup(self, head,k): cur = head count = 0 while cur and count!= k: cur = cur.next count += 1 if count == k: cur = self.reverseKGroup(cur, k) print("cur.val=",cur.val) while count: print("head.val=",head.val) tmp = head.next head.next = cur cur = head head = tmp count -= 1 head = cur return head
代碼來源:
作者:powcai
鏈接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group/solution/kge-yi-zu-fan-zhuan-lian-biao-by-powcai/
來源:力扣(LeetCode)
為了加深理解,圖為自己所作。