LeetCode | Partition List
来源:互联网 发布:淘宝客服图片图片发出 编辑:程序博客网 时间:2024/06/06 09:37
题目:
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal tox.
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
.
思路:
准备两个指针,一个保存小于target的节点,一个保存大于等于target的节点。循环一次完成整个算法。代码:
/** * 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) { // Start typing your C/C++ solution below // DO NOT write int main() function ListNode * lt=NULL; ListNode * p1=NULL; ListNode * gt=NULL; ListNode * p2=NULL; ListNode * p=head; while(p != NULL) { if(p->val < x) { if(lt == NULL) { lt = p; p1 = lt; } else { p1->next = p; p1 = p1->next; } p = p->next; p1->next = NULL; } else { if(gt == NULL) { gt = p; p2 = gt; } else { p2->next = p; p2 = p2->next; } p = p->next; p2->next = NULL; } }; if(p1 == NULL) { return gt; } else { p1->next = gt; return lt; } }};
- 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
- 发送H248数据包流程
- 【leetcode】Partition List
- hdu4751 two-sat
- 接收H248数据包流程
- UDP全面分析
- LeetCode | Partition List
- 数图匹配
- hdu 4750 Count The Pairs 最小生成树
- HQL fetch
- 黑马程序员_日记03(网络编程)
- 框架初始化流程
- 框架初始化
- hdu 4751 Divide Groups 染色
- 物理端点上电注册分析