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.
classSolution: defreverseKGroup(self, head: ListNode, k: int) -> ListNode: if k==1or head==None: return head stack=[] p=head; #存入栈中 for i in range(k): if p==None: return head stack.append(p); p=p.next #逆序 for i in range(k-1, 0, -1): stack[i].next=stack[i-1] #和后一段相连, python递归要self.reverseKGroup() stack[0].next=self.reverseKGroup(p, k) #每次递归返回头节点 return stack[k-1]
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None classSolution: defreverseKGroup(self, head: ListNode, k: int) -> ListNode: if k==1: return head front=head for i in range(k): if front!=None: front=front.next else: return head front=rear=head #front指向第一个节点, rear指向k+1个节点 for i in range(k): if i==k-1: head=rear rear=rear.next #pre是前一段最后一个节点 pre=ListNode(0); whileTrue: p=front q=front.next s=q.next while q!=rear: q.next=p p=q q=s #这里要注意rear可能是NULL, s->next需判断 if s==rear and s==None: break else: s=s.next #本段和后一段相连,此时q=rear, s=rear->next, front.next=rear #前面一段和本段第一个节点相连 pre.next=p pre=front #新front和rear front=rear; for i in range(k): #rear可能没到目标就成了NULL if rear==None: return head rear=rear.next return head;