地址:https://leetcode.com/problems/partition-list/
题目:
Given a linked list and a value x x x, partition it such that all nodes less than x x x come before nodes greater than or equal to x x 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
理解:
给了一个链表,一个x
,要求把这个链表分为两部分,前面是小于x
的,后面是大于等于x
的,且不能改变原来的相对顺序。
实现:
lessPre
:小于部分的尾指针
morePre
:大于等于部分的尾指针
lessHead
:小于部分的头指针
moreHead
:大于等于部分的头指针
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode* lessPre = nullptr;
ListNode* morePre = nullptr;
ListNode* lessHead = nullptr;
ListNode* moreHead = nullptr;
ListNode* p = head;
while (p) {
if (p->val < x) {
if (!lessHead) {
lessHead = p;
lessPre = p;
}
else {
lessPre->next = p;
lessPre=lessPre->next;
}
}
else {
if (!moreHead) {
moreHead = p;
morePre = p;
}
else {
morePre->next = p;
morePre = morePre->next;
}
}
p = p->next;
}
if (lessHead) {
lessPre->next = moreHead;
if(moreHead)
morePre->next = nullptr;
return lessHead;
}
else if (moreHead) {
morePre->next = nullptr;
return moreHead;
}
else
return nullptr;
}
};
可以考虑用带头结点的链表,能够简化很多操作。
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode* lessHead = new ListNode(0);
ListNode* moreHead = new ListNode(0);
ListNode* lessPre = lessHead;
ListNode* morePre = moreHead;
ListNode* p = head;
while (p) {
if (p->val < x) {
lessPre->next = p;
lessPre=lessPre->next;
}
else {
morePre->next = p;
morePre = morePre->next;
}
p = p->next;
}
lessPre->next = moreHead->next;
morePre->next = nullptr;
return lessHead->next;
}
};