mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
33 lines
1.3 KiB
Markdown
33 lines
1.3 KiB
Markdown
![]() |
# [86. Partition List](https://leetcode.com/problems/partition-list/)
|
|||
|
# 思路
|
|||
|
题目要求将链表中小于x的元素移动最前面来,要求保持元素间的相对位置不变。
|
|||
|
我们可以从前往后遍历链表,将小于x的节点取出来按照顺序组成一个新的链表,遍历完成后将这个新链表放在剩下的链表之前即可。
|
|||
|
为了方便处理我们定义新的链表的头结点为`small_head`,剩下的链表的头结点为`big_head`,然后用指针small指向当前新链表的最后一个节点,用big指向当前剩余链表的最后一个节点。
|
|||
|
时间复杂度O(n),空间复杂度O(1)
|
|||
|
|
|||
|
# C++
|
|||
|
``` C++
|
|||
|
class Solution {
|
|||
|
public:
|
|||
|
ListNode* partition(ListNode* head, int x) {
|
|||
|
ListNode *small_head = new ListNode(-1), *big_head = new ListNode(-1);
|
|||
|
ListNode *small = small_head, *big = big_head;
|
|||
|
while(head){
|
|||
|
if(head -> val < x){
|
|||
|
small -> next = head;
|
|||
|
head = head -> next;
|
|||
|
small = small -> next;
|
|||
|
}
|
|||
|
else{
|
|||
|
big -> next = head;
|
|||
|
head = head -> next;
|
|||
|
big = big -> next;
|
|||
|
}
|
|||
|
}
|
|||
|
small -> next = big_head -> next; // 将这个新链表放在剩下的链表之前
|
|||
|
big -> next = NULL;
|
|||
|
return small_head -> next;
|
|||
|
}
|
|||
|
};
|
|||
|
```
|