Odd Even Linked List
2016-07-20 09:18
246 查看
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 ...
/**
* 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 || !head->next) return head;
ListNode* pre=head;
ListNode* cur=head->next;
while(cur && cur->next)
{
ListNode* temp=pre->next;
pre->next=cur->next;
cur->next=cur->next->next;
pre->next->next=temp;
cur=cur->next;
pre=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.
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.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if(!head || !head->next) return head;
ListNode* pre=head;
ListNode* cur=head->next;
while(cur && cur->next)
{
ListNode* temp=pre->next;
pre->next=cur->next;
cur->next=cur->next->next;
pre->next->next=temp;
cur=cur->next;
pre=pre->next;
}
return head;
}
};
/** * 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 || !head->next) return head; ListNode* odd=head; ListNode* even=head->next; ListNode* even_head=even; while(even && even->next) { odd->next=even->next; odd=odd->next; even->next=odd->next; even=even->next; } odd->next=even_head; return head; } };
相关文章推荐
- 【代码笔记】iOS-账号,密码记住
- php 微信分享自定义标题 图片 描述接口开发
- Android Studio中设置作者和创建日期等注释模板
- [李景山php]thinkphp核心源码注释|Cache.class.php
- MySQL索引之前缀索引和索引选择性
- Android 优雅的为RecyclerView添加HeaderView和FooterView
- 【代码笔记】iOS-账号,密码记住
- css字体家族
- UISwitch 开关状态
- AIDL成长记(1)
- Hadoop:MapReduce作业的生命周期
- hdu 5419(数学期望)
- spark源码导读(一)
- 各种排序算法的总结和比较
- Unity 3D - MipMap
- MYSQL中replace into的用法
- [李景山php]thinkphp核心源码注释|Controller.class.php
- 《统计学习方法》学习笔记(3.1)---对偶问题
- orbslam2(3)-优化
- 各种语言的hello world!