LeetCode/solutions/86. Partition List.md
2019-03-11 23:20:32 +08:00

33 lines
1.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [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;
}
};
```