LeetCode Odd Even Linked List
2016-06-04 10:38
204 查看
题意:给出一个单链表,将位于奇数位和偶数位的分组,重新组成链表,要求空间复杂度为O(1)
思路:用四个结点,其中两个表示奇数链表的头和尾,另外两个表示偶数链表的头和尾,注意,偶数链表的尾可能为空或者不为空,在不为空时,需要将下一结点置为空
代码如下:
class Solution
{
public ListNode oddEvenList(ListNode head)
{
if (null == head) return head;
ListNode oddhead = null;
ListNode oddtail = null;
ListNode evenhead = null;
ListNode eventail = null;
ListNode p = head;
int cnt = 1;
while (p != null)
{
if (1 == cnt % 2)
{
if (null == oddhead)
{
oddhead = p; oddtail = p;
}
else
{
oddtail.next = p;
oddtail = oddtail.next;
}
}
else
{
if (null == evenhead)
{
evenhead = p; eventail = p;
}
else
{
eventail.next = p;
eventail = eventail.next;
}
}
p = p.next;
cnt++;
}
if (eventail != null) eventail.next = null;
oddtail.next = evenhead;
return oddhead;
}
}
思路:用四个结点,其中两个表示奇数链表的头和尾,另外两个表示偶数链表的头和尾,注意,偶数链表的尾可能为空或者不为空,在不为空时,需要将下一结点置为空
代码如下:
class Solution
{
public ListNode oddEvenList(ListNode head)
{
if (null == head) return head;
ListNode oddhead = null;
ListNode oddtail = null;
ListNode evenhead = null;
ListNode eventail = null;
ListNode p = head;
int cnt = 1;
while (p != null)
{
if (1 == cnt % 2)
{
if (null == oddhead)
{
oddhead = p; oddtail = p;
}
else
{
oddtail.next = p;
oddtail = oddtail.next;
}
}
else
{
if (null == evenhead)
{
evenhead = p; eventail = p;
}
else
{
eventail.next = p;
eventail = eventail.next;
}
}
p = p.next;
cnt++;
}
if (eventail != null) eventail.next = null;
oddtail.next = evenhead;
return oddhead;
}
}
相关文章推荐
- MPU866ADS初始化配置
- Network of Schools poj 1236 Kosrarju
- Android_RadioButton,CheckBox
- 关于动态内存和输入输出文件
- Java千百问_07JVM架构(017)_jvm常见配置都有哪些
- UNIX/LINUX删除文件末尾的^M
- 局部内部类如何访问外部类方法中变量
- 每日Scrum(6)
- Java 版本
- 乐学成语——为界面加入淡入淡出的效果
- 使用JSP/Servlet开发系统-课程复习试卷测试分析2
- 【软件工程】持续集成:如何建立百万行级代码的版本构建系统(二)架构拓展
- Android activity属性汇总
- 第二阶段个人总结11
- MyEclipse创建第一个Servlet程序
- cocopods的使用
- NSObjCRuntime, NSZone, NSObject报错Unknown
- java使用ganymed-ssh2-build210.jar实现linuxscp命令。
- iOS 本地通知的实现
- Android自定义RatingBar(评分控件)