328. Odd Even Linked List
2016-05-28 12:59
176 查看
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 …
给的单链表,奇偶相间,所以这样也算取巧了。
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 …
给的单链表,奇偶相间,所以这样也算取巧了。
/** * 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) { return head; } ListNode p1 = head, p2 = head.next, pre = p2; while (p2 != null && p2.next != null) { p1.next = p2.next; p1 = p1.next; p2.next = p1.next; p2 = p2.next; } p1.next = pre; return head; } }
相关文章推荐
- Windows Shell Code编写中级拔高
- C++第6次作业
- DES密码算法
- MATLAB计算矩阵间的欧式距离(不用循环!)
- 结构体作为对象的属性
- Hadoop Serialize(二)
- Apache-Tomcat 和 Apache-Maven配置
- 有关i多线程编程的思考
- linux 部署tomcat
- Apache-Tomcat 和 Apache-Maven配置
- 如何训练自己的编程思路
- github简单使用教程
- Android Dialog 系统样式讲解及透明背景
- Spark streaming源码分析之Job动态生成原理与源码解析
- 软件测试作业四
- HDU 1017 A Mathematical Curiosity
- C++实验6-项目4:字符删除
- win10 内测14352 加入了容器 和docker新功能,想体验的赶快升级
- 注意资源利用 不然导致资源消耗会很严重
- centos mysql开启远程访问