Partition List
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小的node,另一个头节点连接大于等于x的node。最后连接两个链表。
/**
* 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* little_head=new ListNode(-1);
ListNode* large_head=new ListNode(-1);
ListNode* p1=little_head,*p2=large_head;
ListNode* p=head;
while(p!=NULL){
if(p->val<x){
p1->next=p;
p1=p;
}
else{
p2->next=p;
p2=p;
}
p=p->next;
}
p2->next=NULL;
p1->next=large_head->next;
delete large_head;
ListNode* rst=little_head->next;
delete little_head;
return rst;
}
};
本文介绍了一种链表分隔算法,该算法将一个链表根据给定的数值x分成两部分,使得所有小于x的节点出现在大于或等于x的节点之前,并保持原始相对顺序不变。
319

被折叠的 条评论
为什么被折叠?



