328. Odd Even Linked List
2016-02-19 14:36
393 查看
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 ...
Credits:
Special thanks to @DjangoUnchained for adding this problem and creating all test cases.
解题思路:
题目意思是将原来链表中的奇数位置按顺序放在前面,链表中偶数位置的元素紧接着奇数后面。可以维护两个指针odd和even,指向奇数链表头部和偶数链表头部,遍历链表,分别将奇偶元素添加到两个链表中,最后合并。注意要将偶数链表的尾部指向null。
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 ...
Credits:
Special thanks to @DjangoUnchained for adding this problem and creating all test cases.
解题思路:
题目意思是将原来链表中的奇数位置按顺序放在前面,链表中偶数位置的元素紧接着奇数后面。可以维护两个指针odd和even,指向奇数链表头部和偶数链表头部,遍历链表,分别将奇偶元素添加到两个链表中,最后合并。注意要将偶数链表的尾部指向null。
#include<windows.h> #include<iostream> using namespace std; 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=head; ListNode*even=head->next; ListNode*p=odd; ListNode*q=even; ListNode*r=head->next->next; int cnt=1; while(r!=NULL){ if(cnt&1){ p->next=r; p=p->next; } else{ q->next=r; q=q->next; } r=r->next; cnt++; } q->next=NULL; p->next=even; return odd; } }; int main(){ Solution test=Solution(); ListNode*head=new ListNode(1); ListNode*p=head; p->next=new ListNode(2); p=p->next; p->next=new ListNode(3); p=p->next; p->next=new ListNode(4); p=p->next; p->next=new ListNode(5); p=test.oddEvenList(head); while(p!=NULL){ cout<<p->val<<" "; p=p->next; } cout<<endl; system("pause"); return 0; } |
相关文章推荐
- 我的2016年计划
- 区分微信内置浏览器
- iOS学习之Socket使用简明教程- AsyncSocket
- collection.toArray(new String[0])中new String[0]的作用
- Android数据库高手秘籍(七)——体验LitePal的查询艺术
- unity 内存优化
- php 引用详解
- java中transient关键字
- WinCE 下 RETAILMSG 如何能在串口工具(SSCOM) 中输出汉字
- 【转】俞军给淘宝产品经理的分享
- Eclipse搭建SSH(Struts2+Spring3+Hibernate3)框架项目教程
- 简单爬虫模拟登陆phpmyadmin
- CentOS常用的文件操作命令总结
- spring初步学习---注入配置文件变量
- UE4 AnimMontage
- 深入理解cookie与session
- Android数据库高手秘籍(六)——LitePal的修改和删除操作
- hdu java 2148
- MySQL监控系统Lepus的搭建
- Zookeeper 修改heap size