leetCode(10):Partition List
2015-06-18 09:08
316 查看
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的链表单独取出组成新的链表,然后把两个链表相连。
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的链表单独取出组成新的链表,然后把两个链表相连。
/** * 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) { if(head==NULL || head->next==NULL) return head; ListNode* p=head; ListNode* preP=head; ListNode* newHead=NULL; ListNode* newP=newHead; while(p) { if(p->val < x) { ListNode* tmp=p->next; if(p==head) { head=tmp; preP=tmp; } if(!newHead) { newHead=p; newHead->next=NULL; newP=newHead; } else { newP->next=p; newP=newP->next; newP->next=NULL; } if(preP!=tmp) preP->next=tmp; p=tmp; } else { if(preP!=p) preP=preP->next; p=p->next; } } if(!newHead) return head; newP->next=head; return newHead; } };
相关文章推荐
- mysql忘记root密码或报错:ERROR 1044 (42000): Access denied for user ”@’localhost’ to database ‘xx‘
- leetCode(10):Partition List 分类: leetCode 2015-06-18 09:08 105人阅读 评论(0) 收藏
- 括号配对问题
- 由asp的一个错误,看语言的不同:asp & java
- centos下Unix网络编程的源码的使用问题
- 【剑指offer】面试题12、打印 1 到最大的 n 位数
- chrome 显示图片遇到的问题,与 淘宝图片服务器 缓存 有关系
- navigationcontroller手势翻页和navigationbar
- 平衡车跌倒 雷军能扶起这个阿斗吗?
- Ogre基础教程5:有缓冲输入
- 用位运算实现四则运算之加减乘除
- 谈谈iOS中粘性动画以及果冻效果的实现
- C++ Primer Plus学习笔记三(第四章)
- android端手机测试体系 (转)
- 获取硬件资源
- asp 调用 vb(activex dll) ,参数传递(传引用)需要注意
- easyUI datagrid 查询方法
- Android中的Handler01
- SVN老是清理失败,显示清理乱码
- SVN老是清理失败,显示清理乱码