LeetCode-- Partition List
来源:互联网 发布:网络歌曲偷菜歌 编辑:程序博客网 时间:2024/06/08 00:48
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.
思路:刚学完数组的快速排序算法,就遇到了这个链表的partition问题,不过我感觉貌似比数组的简单。首先遍历链表,找到比基准元素大的第一个数,然后从这里开始,比基准元素大的数不管,比基准元素小的数用尾插法插入到pre的后面,画图容易理解。
/** * 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* dummy=new ListNode(-1); dummy->next=head; ListNode* pre=dummy,*cur=head; while(pre->next&&pre->next->val<x) pre=pre->next; cur=pre; while(cur->next){ if(cur->next->val<x){ ListNode* tmp=cur->next; cur->next=tmp->next; tmp->next=pre->next; pre->next=tmp; pre=pre->next; } else{ cur=cur->next; } } return dummy->next; }};
阅读全文
0 0
- LeetCode: Partition List
- LeetCode Partition List
- LeetCode: Partition List
- [Leetcode] Partition List **
- [Leetcode] Partition List
- [LeetCode] Partition List
- leetcode 81: Partition List
- [Leetcode] Partition List
- leetcode 118: Partition List
- [LeetCode]Partition List
- [leetcode]Partition List
- LeetCode-Partition List
- [leetcode] Partition List
- LeetCode - Partition List
- [LeetCode] Partition List
- LeetCode 86: Partition List
- LeetCode:Partition List
- 【leetcode】Partition List
- oracle :查询表的字段和字段注释。
- opencv学习笔记(四)识别线段与圆形
- 使用 NAT 将 Linux network namespace 连接外网
- 用js输入一个三位数字计算三位数字的和
- 系统之家(win7系统比较好用)
- LeetCode-- Partition List
- Filter与Servlet的区别和联系
- JAVA中常用IO流类:FileInputStream和FileOutputStream
- Android 开发中,进入软件后判断网络状态
- xfire webservice返回xml
- iOS11.0后APP的图标和启动图
- 一步一步教你VMWare安装苹果Mac OS X
- 为什么很少见程序员炫富?
- minSdk(API 26) > deviceSdk(API 17)