前置题目:
NC78反转链表
NC21链表内指定区间反转
这道题每次先尝试往后走k步,如果不能走到k步的话就说明剩下的节点不足k个了,直接返回。
如果能走k步,就说明这一段的区间可以反转,其实也就转化为了链表内指定区间反转。
下面是图示
确定要反转的区间
反转
确定要反转的区间
反转
没办法往后走k步了, 程序结束
c++
class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { ListNode * front = new ListNode(-1); front->next = head; ListNode * pre = front; ListNode * now = head; ListNode * next = NULL; ListNode * rStart = pre; while(now!=NULL) { ListNode * rStart = pre; ListNode * temp = rStart; for(int i = 0 ; i < k ; i++)//先走k步看一下 { temp = temp->next; if(temp==NULL){return front->next;} } rStart->next = temp; ListNode *tpre = now; pre = temp->next; for(int i = 0 ; i < k ; i++) { next = now->next; now->next = pre; pre = now; now = next; } pre = tpre; } return front->next; } };
java
import java.util.*; public class Solution { public ListNode reverseKGroup (ListNode head, int k) { ListNode front = new ListNode(-1); front.next = head; ListNode pre = front; ListNode now = head; ListNode next = null; while(now!=null) { ListNode rStart = pre; ListNode temp = rStart; for(int i = 0 ; i < k ; i++)//先走k步看一下 { temp = temp.next; if(temp==null){return front.next;} } rStart.next = temp; ListNode tpre = now; pre = temp.next; for(int i = 0 ; i < k ; i++) { next = now.next; now.next = pre; pre = now; now = next; } pre = tpre; } return front.next; } }
python
class Solution: def reverseKGroup(self , head , k ): front =ListNode(-1) front.next = head pre = front now = head nexts = None while now!=None: rStart = pre temp = rStart for i in range(k): temp = temp.next if temp==None: return front.next rStart.next = temp tpre = now pre = temp.next for i in range(k): nexts = now.next now.next = pre pre = now now = nexts pre = tpre return front.next