Leetcode Odd Even Linked List
2016-07-20 03:43
399 查看
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
Difficulty: Medium
/**
* 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 oddTail = head;
ListNode curr = head.next.next, pre = head.next, next = curr.next;
while(curr != null){
next = curr.next;
pre.next = next;
curr.next = oddTail.next;
oddTail.next = curr;
oddTail = oddTail.next;
if(next == null) break;
curr = next.next;
pre = next;
}
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.
Difficulty: Medium
/**
* 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 oddTail = head;
ListNode curr = head.next.next, pre = head.next, next = curr.next;
while(curr != null){
next = curr.next;
pre.next = next;
curr.next = oddTail.next;
oddTail.next = curr;
oddTail = oddTail.next;
if(next == null) break;
curr = next.next;
pre = next;
}
return head;
}
}
相关文章推荐
- 重建控制文件后,各文件(datafile、control file、redo log)中scn的关系
- selenium 多线程
- Reorder List
- Leetcode Remove Duplicates from Sorted List
- Leetcode Path Sum
- Leetcode Power of Two/Three/Four
- Leetcode Rotate Image
- 最小边割集
- 云服务器上安装配置Filezilla Server的坑!
- 在安装Ubuntu的MacBook上更改Apple 键盘模式
- 算法日记(Java实现)第20160719(5)期——POJ1008
- 在MacBook Pro 12-1 with ubuntu 15.10 上安装风扇控制器(mbpfan)
- HDU5723 2016 Multi-University Training Contest 1 (最小生成树+dfs)
- 百度地图API 地理位置获取和大头针显示当前位置
- KVM的网络Networking-qemu-kvm和openvswitch原型环境部署和基本测试 (3)
- 创建虚拟机-qemu-kvm和openvswitch原型环境部署和基本测试 (2)
- 基于栈数据结构的算法(poj-布尔表达式)
- git push 提示输入用户名和密码
- qemu-kvm和openvswitch安装部署-qemu-kvm和openvswitch原型环境部署和基本测试 (1)
- Leetcode 33, 81 Search in Rotated Sorted Array I, II