LeetCode刷题: Odd Even Linked List
2016-02-05 16:40
459 查看
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 ...
我的C++实现:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if( head==NULL || head->next==NULL)
{
return head;
}
ListNode *odd, *even, *even_head;
odd = head;
even_head = even = head->next;
while(even->next)
{
odd->next = even->next;
odd = odd->next;
if(odd->next)
{
even->next = odd->next;
even = even->next;
}
else
{
even->next = NULL;
}
}
odd->next = even_head;
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 ...
我的C++实现:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if( head==NULL || head->next==NULL)
{
return head;
}
ListNode *odd, *even, *even_head;
odd = head;
even_head = even = head->next;
while(even->next)
{
odd->next = even->next;
odd = odd->next;
if(odd->next)
{
even->next = odd->next;
even = even->next;
}
else
{
even->next = NULL;
}
}
odd->next = even_head;
return head;
}
};
相关文章推荐
- 主机是否扫描之fping
- python 11期 第八天
- C# DataTable 和List之间相互转换的方法
- 图(最小生成树) MST 3
- UVa 1594 Ducci Sequence
- a
- 【模拟】【计算几何】[ZJOI2008][HYSBZ/BZOJ1033]杀蚂蚁antbuster
- C/C++重复定义问题的由来和解决方法
- 安装Caffe-Windows
- java反射快速入门(二)
- 安卓开发实例代码
- RSS订阅
- RHEL 6.5 x64bit下expect命令的安装
- JavaScript 覆盖document.createElement 方法 解决window.close在火狐下不兼容问题)
- 网络通信基本原理
- 深度学习硬件指南(号称最全)
- centos创建ssh key
- C# 的List<T>筛选数据填充到另一个List<T>
- java try catch
- List<T>排序,java和c#都用得到