LeetCode Algorithms #328 <Odd Even Linked List>
2016-02-02 12:51
357 查看
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 ...
思路:
因为是链表,所以我们可以原地把他们拆分成两个链表(奇数和偶数)。
所以只需要不变动的,记录偶数节点链表头部信息的指针,一个不断更新的、用于记录偶数节点链表尾部的指针,和一个不断更新的、用于记录奇数节点链表尾部的指针,就可以完成拆分。
然后合并到一起即可。
解:
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* oddTail = head; ListNode* evenHead = head->next; ListNode* evenTail = evenHead; while(evenTail && evenTail->next) { oddTail->next = evenTail->next; oddTail = oddTail->next; evenTail->next = oddTail->next; evenTail = evenTail->next; } oddTail->next = evenHead; return head; } };
相关文章推荐
- google protobuf在ubuntu上安装使用步骤
- go 简单爬虫
- 分布式基础通信协议:paxos,totem和gossip
- go语言基础概要
- Ubuntu,Mac安装go
- Django使用Profile扩展User模块
- Algorithms(week 1,普林斯顿大学公开课)
- LeetCode Algorithms #235 <Lowest Common Ancestor of a Binary Search Tree>
- VIEWGOOD(远古)边防流媒体视频系统建设项目
- 环境配置
- go lang中的import
- Go语言笔记:base64/sha1的使用
- django学习笔记(四)表单
- m3u文件转pls文件(go语言实现)
- Django时间问题
- Django REST framework的各种技巧【目录索引】
- Django REST framework的各种技巧——6.异常处理
- Django REST framework的各种技巧——7.导入导出
- Django REST framework的各种技巧——5.搜索
- Django REST framework的各种技巧——3.权限