LeetCode: Partition List [086]
来源:互联网 发布:java性能分析工具 编辑:程序博客网 时间:2024/06/14 15:52
【题目】
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
.
【题意】
给定一个链表和一个数值x,将链表中的值按x进行划分,小于x的在前,大于等于x的在后。两部分中节点的之间的相对位置与在原链表中时相同【思路】
先将链表按x分裂成两个链表,一个链表中的值小于x, 另一个链表中的值大于等于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)return head; ListNode*headLess=NULL; ListNode*tailLess=NULL; ListNode*headGreater=NULL; ListNode*tailGreater=NULL; ListNode*pointer=head; while(pointer){ if(pointer->val<x){ if(tailLess==NULL)headLess=pointer; else tailLess->next=pointer; tailLess=pointer; pointer=pointer->next; tailLess->next=NULL; } else{ if(tailGreater==NULL)headGreater=pointer; else tailGreater->next=pointer; tailGreater=pointer; pointer=pointer->next; tailGreater->next=NULL; } } //合并两个链表 if(tailLess){ head=headLess; tailLess->next=headGreater; } else head=headGreater; return head; }};
0 0
- LeetCode: Partition List [086]
- LeetCode 086 Partition List
- 086 Partition List [Leetcode]
- leetcode 086 Partition List
- leetcode 086 —— Partition List
- 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
- C++ map
- 正则表达式
- TOJ 1662 The Fewest Coins -- 动态规划DP
- VBScripts and UAC elevation(visa以后的系统)
- HttpURLConnection跨域、跨应用访问
- LeetCode: Partition List [086]
- GDI+学习笔记----前言
- C++教程网 第26章
- POJ 1038 Bugs Integrated, Inc. 状态压缩DP
- 最小生成树算法汇总 (普里姆 && 克鲁斯卡尔与并查集结合)
- 矩阵链乘法2(15章:动态规划)。。。2014.5.30
- Zero Copy I: User-Mode Perspective (1)
- PCA(Principal Component Analysis)之个人理解
- poj2196