1 题目
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.
Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
2 尝试解
/**
* 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* dummy = new ListNode(0);
dummy->next = head;
ListNode* pre = dummy;
ListNode* cur = dummy;
while(cur->next!=NULL && cur->next->val < x){ //find the node before the first node no less than x,e.g. Node 1 before Node 4
cur = cur->next;
}
if(cur->next == NULL) return dummy->next; //all less than x
pre = cur;
cur = cur->next;
while(cur->next !=NULL){
if(cur->next->val >= x)
cur = cur->next;
else{
ListNode* tochange = cur->next; //pre = 1, cur = 3,tochange = 2
cur->next = cur->next->next; //1->4->3->5->2 | 2
tochange->next = pre->next; //1->4->3->5->2 | 2->4
pre->next = tochange; //1->2->4->3->5->2
pre = pre->next;
}
}
return dummy->next;
}
};
3 标准解
ListNode *partition(ListNode *head, int x) {
ListNode node1(0), node2(0);
ListNode *p1 = &node1, *p2 = &node2;
while (head) {
if (head->val < x)
p1 = p1->next = head;
else
p2 = p2->next = head;
head = head->next;
}
p2->next = NULL;
p1->next = node2.next;
return node1.next;
}