86.Partition List
2015-12-06 21:10
330 查看
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
return
思路:此题的任务是划分链表,比x小的链表节点都出现在比x大或者等于的节点前面,而且还要保持原来的相对位置不要发生变化。我们新建两个链表了l1,l2,遍历原来的链表 ,把值小于x的节点都加入l1,把值大于或者等于x的节点都加入l2,最后将l2连接至l1的后面,所得的链表就是我们所求的结果了。
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given
1->4->3->2->5->2and x = 3,
return
1->2->2->4->3->5.
思路:此题的任务是划分链表,比x小的链表节点都出现在比x大或者等于的节点前面,而且还要保持原来的相对位置不要发生变化。我们新建两个链表了l1,l2,遍历原来的链表 ,把值小于x的节点都加入l1,把值大于或者等于x的节点都加入l2,最后将l2连接至l1的后面,所得的链表就是我们所求的结果了。
/** * 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 *head1,*head2; head1=head2=NULL; ListNode *cur1,*cur2; cur1=cur2=NULL; while(head){ ListNode *cur=head; head=head->next; cur->next=NULL; if(cur->val<x){ if(!head1){ head1=cur; cur1=head1; } else{ cur1->next=cur; cur1=cur1->next; } }else{ if(!head2){ head2=cur; cur2=head2; }else{ cur2->next=cur; cur2=cur2->next; } } } if(!cur1) return head2; cur1->next=head2; return head1; } };
相关文章推荐
- 周练-a—lightoj1148
- OC-控制结构
- java scanner 输入多行
- 封装
- 设计模式学习(一)代理模式
- jquery uploadifive使用
- 森林病虫防治系统 (十二.1)
- java中类的加载机制
- CasperJS学习笔记--循环
- ViewController生命周期
- OC-ARC
- C&C++ 结构体,类 区别
- Imageloader<1>-总体简介
- C++类与对象基础
- 牛客网选择题100题
- spark RDD编程,scala版本
- Go语言中使用MySql数据库
- uva 1218——Perfect Service
- 【Linux编程】用select处理普通数据和带外数据
- OC-引用计数