LeetCode---(86) Partition List
2015-05-19 20:07
465 查看
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的节点的前面,而且,不能改变原来节点的前后位置。
思路:设置两个链表,一个用于存放值小于x的节点,一个用于存放值不小于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的所有节点均放在不小于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 NULL; ListNode* p=head; ListNode* L1=new ListNode(0); ListNode* p1=L1; ListNode* L2=new ListNode(0); ListNode* p2=L2; while(p!=NULL) { if(p->val<x) { ListNode* q=new ListNode(p->val); p1->next=q; p1=p1->next; } else { ListNode* q=new ListNode(p->val); p2->next=q; 99b3 p2=p2->next; } p=p->next; } p1->next=L2->next; return L1->next; } };
相关文章推荐
- LeetCode题解-86-Partition List
- LeetCode 86 Partition List
- LeetCode - 86 - Partition List
- [LeetCode]86 Partition List
- leetcode 86:Partition List
- LeetCode86 Partition List
- LeetCode 86 Partition List
- LeetCode 86: Partition List
- Leetcode 86 Partition List
- LeetCode(86) Partition List
- leetcode[86]Partition List
- [leetcode 86] Partition List
- leetcode-Partition List-86
- LeetCode(86) Partition List
- LeetCode 86 Partition List
- LeetCode86 Partition List
- [Leetcode 71] 86 Partition List
- LeetCode 86 Partition List (Python详解及实现)
- [LeetCode 86] Partition List
- leetcode_86_Partition List