Leetcode:328. Odd Even Linked List
2016-07-26 23:44
281 查看
328. Odd Even Linked List QuestionEditorial Solution My Submissions
Total Accepted: 38481
Total Submissions: 96844
Difficulty: Medium
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 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 ...
思路:使用两个头指针交替进行,最后将偶指针连接在奇指针后面。该方法效率较高,运算速度为16ms,击败96%提交。
Total Accepted: 38481
Total Submissions: 96844
Difficulty: Medium
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 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 ...
思路:使用两个头指针交替进行,最后将偶指针连接在奇指针后面。该方法效率较高,运算速度为16ms,击败96%提交。
class Solution { public: ListNode* oddEvenList(ListNode* head) { if(head==NULL ||head->next==NULL) return head; ListNode* oddhead=head; ListNode* evenhead=head->next; ListNode* sechead=head->next; int i=1; while(oddhead&&evenhead) { if(i%2==1) { if(evenhead->next) { oddhead->next=evenhead->next; oddhead=oddhead->next; } else evenhead=evenhead->next; i++; } else { if(oddhead->next) { evenhead->next=oddhead->next; evenhead=evenhead->next; } else { evenhead->next=NULL; break; } i++; } } oddhead->next=sechead; return head; } };
相关文章推荐
- HDU5762 多校联合3 Teacher Bo
- 深入JVM 第一章 之2
- SecureCRT 7.3.4破解版(含注册机)
- IO流_part2
- (转) OpenCV学习笔记大集锦 与 图像视觉博客资源2之MIT斯坦福CMU
- iOS 屏幕比例缩放 ScaleLayout
- javaScript操作cookie
- 【学习笔记】 C++里面的绑定类型
- python(三) 大数加法
- 屏幕录像工具之屏幕截图
- Android Unlock Patterns
- HelloWorld
- Linux下搭建一个简单的UDP通信
- 多线程编程——临界区
- iOS开发 -文件下载(下载功能的封装)
- IO流_part1
- mybatis做like模糊查询
- 三.可选项和控制流
- 剑指offer——平衡二叉树
- java编程---3.2 (关于String的练习题) 统计字符串中每个字符的个数,例如:把aaaabbaaccbb变成a6b4c2