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.
*
*
************************************************************************/
关于交换对节点的解析如下:
这里写图片描述

完整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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值