LeetCode Swap Nodes in Pairs
题意:给出一个单链表,每两个一组相互交换,不能通过交换每组的值来实现
思路:
1、链表为空或者只有一个结点,不需要交换
2、有两个结点时p,q,其中q = p.next,交换用p.next = q.next,q.next = p
3、在有多于2个结点时,以4个为例,前一组交换后的结点的后继结点应该是后一组结点未交换前的第二个
具体代码如下:
class ListNode
{int val;ListNode next;ListNode(int x) { val = x;}
}class Solution
{public ListNode swapPairs(ListNode head){if (null == head || null == head.next) return head;ListNode cur = head, next = cur.next;ListNode newHead = next;cur.next = next.next;next.next = cur;if (null == cur.next) return newHead;while (cur.next.next != null){ListNode pre = cur;cur = cur.next;next = cur.next;pre.next = next;cur.next = next.next;next.next = cur;if (null == cur.next) break;}return newHead;}
}
LeetCode Swap Nodes in Pairs相关推荐
- LeetCode Swap Nodes in Pairs题目的一种简洁解法
这题目比较简单,看了很多结题方法都是新建链表,但也可以使用递归方法,代码量非常少. class Solution { public: ListNode* swapPairs(ListNode* ...
- 【重点】LeetCode 24. Swap Nodes in Pairs
LeetCode 24. Swap Nodes in Pairs 参考网址:http://www.cnblogs.com/grandyang/p/4441680.html 此题算是链表中比较考察细节的 ...
- 24. Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head. You may not modify the value ...
- LeetCode 24 Swap Nodes in Pairs(交换序列中的结点)
翻译 给定一个链表,调换每两个相邻节点,并返回其头部.例如, 给定 1->2->3->4, 你应该返回的链表是 2->1->4->3.你的算法必须使用唯一不变的空间 ...
- LeetCode 24 Swap Nodes in Pairs (交换相邻节点)
题目链接: https://leetcode.com/problems/swap-nodes-in-pairs/?tab=Description Problem: 交换相邻的两个节点 如上图所示,递归 ...
- [leetcode] 24. Swap Nodes in Pairs
题目 Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1-> ...
- Leetcode 24——Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2-& ...
- Leetcode 24. Swap Nodes in Pairs
不定期更新leetcode解题java答案. 采用pick one的方式选择题目. 本题很简单,大致翻译过来的意思是将单链表相邻节点互换节点位置.额外的要求是使用O(1)空间,以及不修改节点值,仅对节 ...
- leetcode 24. Swap Nodes in Pairs | 24. 两两交换链表中的节点(Java)
题目 https://leetcode.com/problems/swap-nodes-in-pairs/ 题解 两两翻转,链表题 so easy /*** Definition for singly ...
最新文章
- 第一代狗狗币教父联合社区挽救狗狗币,并在国内布道狗狗币三年之久
- 买股票的最佳时机(六种题解dp)
- CentOS 6.X 关闭不需要的 TTY 方法
- redis cli 删除key 模糊_Redis集群及雪崩
- python php perl,python 调用 php 范例
- 基于 WPF 模块化架构下的本地化设计实践
- linux安装 icc编译器,安装 Intel Compiler (ifort icc icpc)
- 坐标不显示_Simpack不显示坐标轴方向的解决方法
- java random.nextbytes_Java Random类
- (49)Xilinx Subtracter IP核配置(十)(第10天)
- 能帮你找到网页设计灵感的16个网站
- 词法分析 有穷自动机
- 360安全卫士对于易量安装打包的可执行程序进行病毒误报
- 产品经理的段位——说说腾讯的产品职级
- CAD制图软件中动态块功能的使用技巧
- 2021-08-13
- static 在C/C++中的用法总结
- 法国奢侈品牌VILEBREQUIN限时精品店登陆北京老佛爷百货
- 苹果服务器系统状态查询网址
- 转自汇编网: 高三老师给大一学生的一封信(感动!)
热门文章
- 一款图像相关软件PhoXo
- 用 Shell 脚本访问 MySQL 数据库
- android 点击扩散,Android水波纹扩散效果
- 装python对电脑有什么影响-你知道:重装系统对电脑有什么影响吗?会损坏电脑吗?...
- python爬虫入门代码-Python爬虫入门
- python.freelycode.com-Python日期时间处理: datestuff
- python基础代码库-python基础:一个非常简单且详细的多线程代码
- python散点图点的大小-Java 学习之路
- 学会python编程容易吗-学习武汉Python编程培训容易吗?别人都是怎么学习的?
- python编程培训多少钱-想要学习Python,武汉Python编程培训费用是多少?