题目
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.
简单说来,给定一个链表和一个值x
要求:链表中小于x的值全部位于大于等于x的值的左边,且相对位置不变
example
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
方案1
- 遍历整个数组
- 遇到小于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 head;
}
else{
ListNode *small=NULL;
ListNode *big=NULL;
ListNode *cur=head;
while(cur!=NULL){
if(cur->val<x){
if(small==NULL){
if(big==NULL){
small=cur;
cur=cur->next;
continue;
}
else{
ListNode *newnode=new ListNode(cur->val);
newnode->next=head;
head=newnode;
small=newnode;
ListNode *del=cur;
big->next=cur->next;
cur=cur->next;
delete del;
continue;
}
}
else{
if(cur==small->next){
small=cur;
cur=cur->next;
continue;
}
else{
ListNode *newnode=new ListNode(cur->val);
ListNode *tmp=small->next;
small->next=newnode;
newnode->next=tmp;
small=newnode;
ListNode *del=cur;
big->next=cur->next;
cur=cur->next;
delete del;
continue;
}
}
}
big=cur;
cur=cur->next;
}
return head;
}
}
};
方案二
- 代码来自讨论区
https://leetcode.com/problems/partition-list/discuss/29185/Very-concise-one-pass-solution
- 看到题目,最朴素的想法是将所有小于x的值重新建一个链表,将大于等于x的值建一个链表,但是考虑到链表指针的特性,我们完全没有必要重新申请整个链表的空间,直接利用原来的即可
- 时间花费较小
class Solution {
public:
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;
}
};