LeetCode24 Swap Nodes in Pairs 25. Reverse Nodes in k-Group详解

/************************************************************************
*
* Given a linked list, swap every two adjacent nodes and return its head.
*
* For example,
* Given 1->2->3->4, you should return the list as 2->1->4->3.
*
* Your algorithm should use only constant space. You may not modify the values in the list,
* only nodes itself can be changed.
*
*
************************************************************************/
关于交换对节点的解析如下:
LeetCode24 Swap Nodes in Pairs 25. Reverse Nodes in k-Group详解_第1张图片

完整AC代码

    ListNode* swapPairs(ListNode* head) {
        ListNode preHead(0), *pre = &preHead;
        ListNode *cur = head;
        pre->next = head;
        while (cur&&cur->next)
        {
            ListNode* nxt = cur->next;
            cur->next = nxt->next;
            nxt->next = pre->next;
            pre->next = nxt;
            pre = cur;
            cur = cur->next;
        }
        return preHead.next;
    }

/************************************************************************
*
* Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
*
* If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
*
* You may not alter the values in the nodes, only nodes itself may be changed.
*
* Only constant memory is allowed.
*
* For example,
* Given this linked list: 1->2->3->4->5
*
* For k = 2, you should return: 2->1->4->3->5
*
* For k = 3, you should return: 3->2->1->4->5
*
*
************************************************************************/

与上一题基本相同,区别就是要知道链表的长度,当剩余链表的长度小于k是,就不需要做了。

AC代码

ListNode *reverseKGroup(ListNode *head, int k) {
        if (!head || k == 1) return head;
        int listLen = 0;
        ListNode preHead(0);
        preHead.next = head;
        ListNode* cur = &preHead, *pre = &preHead, *next = NULL;
        while (cur = cur->next) listLen++;
        while (listLen >= k) {
            cur = pre->next;
            next = cur->next;
            for (int i = 0; i < k - 1; i++) {
                cur->next = next->next;
                next->next = pre->next;
                pre->next = next;
                next = cur->next;
            }
            pre = cur;
            listLen -= k;
        }
        return preHead.next;
    }

你可能感兴趣的:(LeetCode)