LeetCode--No.328--Odd Even Linked List
2016-06-05 04:53
417 查看
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
Example:
Given
return
Note:
The relative order inside both the even and odd groups should remain as it was in the input.
The first node is considered odd, the second node even and so on ...
思路:新建一个存储偶数的列表,参数有h2与p2,h2不动,永远指向该列表表头,p2指向该列表对尾。
head指向原列表表头,p1指向原列表尾部。
边界检测比较恶心。但觉得自己代码写的太啰嗦。从网上又没有看到满意的答案。只能先这样吧。希望日后如果某天我变牛了=。=,可以重新改下这个代码,写的漂亮些。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode oddEvenList(ListNode head) {
if(head == null || head.next == null || head.next.next == null)
return head;
ListNode p1 = head;
ListNode p2 = head.next;
ListNode h2 = p2;
p1.next = p1.next.next;
p1 = p1.next;
while(p1.next != null && p1.next.next != null){
p2.next = p1.next;
p1.next = p1.next.next;
p1 = p1.next;
p2 = p2.next;
}
if (p1.next != null){
p2.next = p1.next;
p2 = p2.next;
}
p1.next = h2;
p2.next = null;
return head;
}
}
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
Example:
Given
1->2->3->4->5->NULL,
return
1->3->5->2->4->NULL.
Note:
The relative order inside both the even and odd groups should remain as it was in the input.
The first node is considered odd, the second node even and so on ...
思路:新建一个存储偶数的列表,参数有h2与p2,h2不动,永远指向该列表表头,p2指向该列表对尾。
head指向原列表表头,p1指向原列表尾部。
边界检测比较恶心。但觉得自己代码写的太啰嗦。从网上又没有看到满意的答案。只能先这样吧。希望日后如果某天我变牛了=。=,可以重新改下这个代码,写的漂亮些。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode oddEvenList(ListNode head) {
if(head == null || head.next == null || head.next.next == null)
return head;
ListNode p1 = head;
ListNode p2 = head.next;
ListNode h2 = p2;
p1.next = p1.next.next;
p1 = p1.next;
while(p1.next != null && p1.next.next != null){
p2.next = p1.next;
p1.next = p1.next.next;
p1 = p1.next;
p2 = p2.next;
}
if (p1.next != null){
p2.next = p1.next;
p2 = p2.next;
}
p1.next = h2;
p2.next = null;
return head;
}
}
相关文章推荐
- startForeground()让服务保持前台级别
- linux下下安装jdk-6u45-linux-x64.bin
- 点击文字,弹出层
- Ubuntu 16.04 卸载vmware
- 第二阶段个人博客总结8
- C++重载,重写,重定义
- MySQL数据库读写分离、读负载均衡方案选择
- Number of Islands, variation
- oracle错误代码大全
- 第13课:Spark Streaming源码解读之Driver容错安全性
- Ubuntu 安装开源微信(源码安装+release快速安装)
- x64通过PspCidTable遍历进程
- 5.2 网络训练
- LeetCode--No.206--Reverse Linked List
- LeetCode 47 Permutations II
- R语言-代码规范(Google's R Style Guide)
- Android Picasso的简单使用
- 详解五大排序算法
- ffmpeg处理RTMP流媒体的命令大全
- 【杭电】[1302]The Snail