328. Odd Even Linked List
2016-02-26 23:51
369 查看
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==NULL)
return NULL;
ListNode* root=head;
ListNode* pre1=head->next;
ListNode* pre=pre1;
while((pre!=NULL)&&(pre->next!=NULL))
{
head->next=pre->next;
head=head->next;
pre->next=head->next;
pre=pre->next;
}
head->next=pre1;
return root;
}
};
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==NULL)
return NULL;
ListNode* root=head;
ListNode* pre1=head->next;
ListNode* pre=pre1;
while((pre!=NULL)&&(pre->next!=NULL))
{
head->next=pre->next;
head=head->next;
pre->next=head->next;
pre=pre->next;
}
head->next=pre1;
return root;
}
};
相关文章推荐
- DirectX SDK 与 DirectShow SDK
- 2016/2/26 jQuery的技术 1,安装 2,语法选择器$ 事件触发 3,常用jQuery函数
- ssh2-hibernate错误小结
- 完美实现tab和Fragment的联动效果
- 19. Remove Nth Node From End of List
- [Leetcode]220. Contains Duplicate III @python
- iOS开发系列--Objective-C之类和对象
- 如何检查内存泄露问题
- Java [Leetcode 136]Single Number
- atitit.编程语言 类与对象的 扩展机制.doc
- atitit.编程语言 类与对象的 扩展机制.doc
- atitit.编程语言 类与对象的 扩展机制.doc
- Pig简单入门
- apache 限制指定user_agent
- 线上Nginx跳转存在的接口返回异常问题
- Atitit.为什么小公司也要做高大上开源项目
- 中介者模式
- Atitit.为什么小公司也要做高大上开源项目
- HTML5 is Canvas
- struts-config.xml文件详解