题目: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,
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.
解析:先声明两个指针result1和result2,遍历链表,当节点小于x的时候,result1指向该节点,当节点大于或等于x的时候,result2指向该节点。最后再把生成的两个链表进行合并即可。
代码:
/**
* 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 *result1=new ListNode(0);
ListNode *result2=new ListNode(0);
ListNode *temp1=result1;
ListNode *temp2=result2;
while(head!=NULL)
{
if(head->val<x)
{
temp1->next=head;
temp1=temp1->next;
}
else
{
temp2->next=head;
temp2=temp2->next;
}
head=head->next;
}
temp1->next=result2->next;
temp2->next=NULL;
return result1->next;
}
};