力扣25. K 个一组翻转链表

1.需要画图确定反转的逻辑
2.习惯性地使用pre、cur、nxt三个指针来思路清晰地完成一系列变换
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode() : val(0), next(nullptr) {} 7 * ListNode(int x) : val(x), next(nullptr) {} 8 * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 ListNode* reverse(ListNode *head, ListNode *tail) { //反转区间内链表 14 if (!head || !head -> next) { 15 return head; 16 } 17 ListNode *pre, *cur, *nxt; 18 pre = nullptr, cur = head, nxt = head -> next; 19 while(pre != tail) { // pre == tail时表示已反转完成 20 cur -> next = pre; 21 pre = cur; 22 cur = nxt; 23 if (nxt) nxt = nxt -> next; 24 } 25 return cur; // 返回tail的下一个节点,用作reverseKGroup下一次迭代的头节点 26 } 27 ListNode* reverseKGroup(ListNode* head, int k) { 28 if(!head || !head -> next) { 29 return head; 30 } 31 ListNode *cur = head; 32 for (int i = 1; i < k; ++i) { //遍历完k个后cur指向的就是当前组的尾节点 33 if (cur -> next){ 34 cur = cur -> next; 35 } else { //节点数量不够,不用反转,直接返回头结点即可 36 return head; 37 } 38 } 39 40 ListNode *nxt = reverse(head, cur); 41 head -> next = reverseKGroup(nxt, k); 42 return cur; //返回该组反转后的头结点(即反转前的尾节点) 43 } 44 };
// 统计是否够k个时,这种写法存在问题,会把nullptr作为一个结点进行统计 for (int i = 0; i < k - 1; ++i) { if (!cur) return head; cur = cur -> next; }
浙公网安备 33010602011771号