86. Partition List
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.
Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
题目链接:https://leetcode.com/problems/partition-list/
解法一:构造假头辅助移动
这道题的思路很简单,但在实现上,对如何将节点向前移动的情况上逻辑较为复杂,此时需要一个假头(专业名词:哨兵节点)作为辅助,能避免移动到链头位置和非链头位置的操作不同。曾经也尝试过能否不用假头,但确实比较冗余易错。
代码里conti是用来标识当前遍历到的小于的节点是否处在连续小于的阶段,以便直接跳过,找到最后一个小于和大于的分解节点。实际上这种情况只存在于链开头位置,一但断开后就不再会出现,所以没有必要使用标识变量,可优化成前面加一段找第一个大于节点的while循环。
!tip:假头是链表问题的常用辅助手段,重视起来吧。
/**
* 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 || head->next==NULL) return head;
ListNode *before_head = new ListNode(INT_MIN);
before_head->next = head;
ListNode* cur = head, *next = NULL, *pre = before_head, *begin = before_head;
bool conti = true;
while(cur!=NULL){
next = cur->next;
if(cur->val < x){
if(conti){
begin = cur;
pre = cur;
cur = next;
}else{
pre->next = next;
cur->next = begin->next;
begin->next = cur;
begin = cur;
cur = next;
}
}else{
pre = cur;
cur = next;
conti = false;
}
}
return before_head->next;
}
};
解法二:拆成两个链表
这个解法官方给出,非常巧妙。
直接将遍历的节点分别放到小于的链和大于的链,最后再合并。由于链表只需要next操作指针就可实现,不像数组需要开辟新的空间,思路上非常直接清晰!