【leetcode每日一题】NO86.Partition List
2015-08-16 09:33
218 查看
题目:Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
解析:先声明两个指针result1和result2,遍历链表,当节点小于x的时候,result1指向该节点,当节点大于或等于x的时候,result2指向该节点。最后再把生成的两个链表进行合并即可。
代码:
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
解析:先声明两个指针result1和result2,遍历链表,当节点小于x的时候,result1指向该节点,当节点大于或等于x的时候,result2指向该节点。最后再把生成的两个链表进行合并即可。
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *partition(ListNode *head, int x) { ListNode *result1=new ListNode(0); ListNode *result2=new ListNode(0); ListNode *temp1=result1; ListNode *temp2=result2; while(head!=NULL) { if(head->val<x) { temp1->next=head; temp1=temp1->next; } else { temp2->next=head; temp2=temp2->next; } head=head->next; } temp1->next=result2->next; temp2->next=NULL; return result1->next; } };
相关文章推荐
- protobuf的反射机制
- 股票市场问题(The Stock Market Problem)
- hdu 1150 Machine Schedule 最少点覆盖转化为最大匹配
- OpenCV实现图像锐化
- 简述Java内存泄露
- Android实战简易教程-第三十六枪(监听短信-实现短信验证码自动填入)
- 汤姆猫代码实现
- C语言基础
- House Robber II
- 架构设计要平衡兼顾多方需求
- Activity与Fragment的生命周期
- hdu2883kebab最大流
- GameUnity 2.0 文档(五) 人工智能之---------------Flocking算法 (聚集,分散,列队 )
- 标准c的tmpfile()、tmpfile_s()生成的临时文件究竟放在哪里了?
- IOS实现弹出菜单效果MenuViewController(背景 景深 弹出菜单)
- 标准c的tmpfile()、tmpfile_s()生成的临时文件究竟放在哪里了?
- SQL localdb 连接字符串
- poj 3068 有流量限制的最小费用网络流
- Android(java)学习笔记163:Android开发时候颜色设置是bgr不是rgb
- B. Amr and The Large Array