面试题 02.04. 分割链表
题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/partition-list-lcci/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目分析
新建两个链表 sml_dummy , big_dummy ,分别用于添加所有「节点值 <x」、「节点值 ≥x」的节点。
- 注:
出现下面报错:
原因
没有将链表的最后一个节点的指针置为空。
/**
* 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) {
ListNode *smlDummy = new ListNode(0), *bigDummy = new ListNode(0);
ListNode *smlCur = smlDummy, *bigCur = bigDummy;
ListNode *cur = head;
while(cur){
if(cur->val >= x){
bigCur->next = cur;
bigCur = bigCur->next;
}else{
smlCur->next = cur;
smlCur = smlCur->next;
}
cur = cur->next;
}
smlCur->next = bigDummy->next;
bigCur->next = nullptr;
return smlDummy->next;
}
};