Create 86. Partition List.md

This commit is contained in:
唐树森 2019-03-11 23:20:32 +08:00 committed by GitHub
parent 9e178695ad
commit 68ed924fdc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,32 @@
# [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;
}
};
```