给你一个单链表和一个整数x,调整单链表的元素的位置,使得前半部分的值小于x,后半部分的值大于x。
下面的算法的思路和单链表快速排序的思路是一样的,该算法有可能改变节点的相对顺序。
ListNode *partition(ListNode *head, int x) {
ListNode* slow = head;
ListNode* fast = head;
while(fast)
{
if(fast->val < x) // note the less-than-equal operator here
// Input: 5->4->3 and x = 4
// Output: 4->3->5
{
swap(slow->val, fast->val);
slow = slow->next;
}
fast = fast->next;
}
return head;
}
2. 下面的算法可以保持相对顺序不变。
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.
思路很简单:先找出链表的长度和链表的尾节点,然后遍历链表,如果当前节点的值小于target,跳到下一个节点,如果当前节点的值大于等于target,则把这个节点移动到链表的末端。
/**
* 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 *p= new ListNode(0);
p->next = head;
head = p; // used to save the result head.
ListNode *last=head; // used to get the last node
if (head->next==NULL){return head->next;}
int n=0; //length of the list
while (last->next!=NULL){ last=last->next; n++; } //get the length and last node
while (n>0){ // in case of non-stop loop, count n.
if (p->next->val < x){ // val<x keep the node
p=p->next;
n--;
}else{ // val>=x move to last
last->next = new ListNode(p->next->val); // add node to the last
last = last->next;
p->next = p->next->next; //delete current node
n--;
}
}
return head->next; //the 1st node is elmininated
}
};