LINTCODE——K组翻转链表

时间:2022-02-16 16:24:51

LINTCODE——K组翻转链表

思路:和翻转链表差不多,就是要注意每隔K个值打断、翻转、拼接就好了

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */


class Solution {
public:
    /* * @param head: a ListNode * @param k: An integer * @return: a ListNode */
    ListNode * reverseKGroup(ListNode * head, int k) {
        // write your code here


        ListNode *theadNode = new ListNode(0);
            theadNode -> next = head;
        ListNode *resNode = theadNode;
        ListNode *curNode = head;
        int cnt = 0;
        while(curNode != NULL)
        {
            cnt++;
            if(cnt == k)
            {
                //打断
                ListNode *tcurNode = curNode;
                curNode =  curNode -> next;
                tcurNode -> next = NULL;
                //翻转
                head = reverse(head);

                //拼接
                theadNode -> next = head;
                ListNode *tail = head;
                while(tail->next)
                    tail = tail->next;
                tail -> next = curNode;

                //重新定义头节点
                theadNode = tail;
                head = curNode;

                cnt = 0;
                continue;

            }

            curNode =  curNode -> next;

        }
        return resNode -> next;


    }
    ListNode *reverse(ListNode *head)
    {
        if(head == NULL)
            return head;
        ListNode *curNode = head;
        ListNode *preNode = NULL;
        while(curNode != NULL)
        {
            ListNode *nextNode = curNode -> next;
            curNode -> next = preNode;
            preNode = curNode;
            curNode = nextNode;
        }
        return preNode;

    }
};