25. K 个一组翻转链表

2020-08-15 21:21发布

25. K 个一组翻转链表

难度困难651给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
 
示例:
给你这个链表:1->2->3->4->5
当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5
 
 
思路:添加哑巴节点,即虚拟 head 节点 head_res 节省代码量。
 
代码:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode *current, *after, *head_res, *first, *temp, *pre;
        current = head;//current = 1
        if(k==1||head==NULL||head->next==NULL)
            return head;
        head_res = new ListNode;
        head_res->next = head;
        pre = head_res;
        int size = 0;
        current = head;
        while(current!=NULL)
        {
            current = current->next;
            size++;
        }
        int i, j;
        for(j = 1; j <= size/k; j++)
        {
            current = pre->next; //current = 3
            after = current->next; //after = 4
            first = current; //first = 3
            for(i = 1; i <= k-1; i++)
          {
            temp = after->next;//temp = 5
            after->next = current;//4->3 
            current = after;//current = 4
            after = temp;//after = 5
          }
          pre->next = current;//1->3
          first->next = after;//3->5
          pre = first;//pre = 3

        }
        return head_res->next;
        delete(head_res);

        
    }
};

 

标签: