博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode24 Swap Nodes in Pairs 25. Reverse Nodes in k-Group详解
阅读量:4186 次
发布时间:2019-05-26

本文共 2191 字,大约阅读时间需要 7 分钟。

/************************************************************************

*
* 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;    }
你可能感兴趣的文章
程序员身上有异味,同事为什么都不会直接告诉他?
查看>>
大数据折射算法“歧视”?王思聪微博抽奖113位,仅有一位男性
查看>>
Java、C、C+ +、PHP、Python分别用来开发什么?一篇文章告诉你!
查看>>
Linux-ACL权限介绍
查看>>
Linux -文件系统
查看>>
Linux常用命令-进程管理
查看>>
Linux - 定时任务
查看>>
Linux - SHELL基础
查看>>
Linux-SHELL基础语法
查看>>
Linux-SHELL变量
查看>>
Linux-SHELL常用命令
查看>>
Linux-网络运维基础
查看>>
Linux网络运维-SSH
查看>>
Linux网络运维 -- 配置DHCP服务器
查看>>
Android开发问题记录
查看>>
Verilog编程网站学习——门电路、组合电路、时序电路
查看>>
android——学生信息显示和添加
查看>>
Android——ImageSwitcher轮流显示动画
查看>>
Android——利用手机端的文件存储和SQLite实现一个拍照图片管理系统
查看>>
图像调优1:清晰度相关参数MTF,SFR,MTF50,MTF50P 以及TVL的概念以及换算说明
查看>>