问题描述:
给你一个链表的头节点 head
和一个特定值 x
,请你对链表进行分隔,使得所有 小于 x
的节点都出现在 大于或等于 x
的节点之前。
你不需要 保留 每个分区中各节点的初始相对位置。
示例 1:
输入:head = [1,4,3,2,5,2], x = 3 输出:[1,2,2,4,3,5]
示例 2:
输入:head = [2,1], x = 2 输出:[1,2]
提示:
- 链表中节点的数目在范围
[0, 200]
内 -100 <= Node.val <= 100
-200 <= x <= 200
解决方案:
1、比 X 大的在右边,小的在左边,X 的位置无所谓。
2、使用 2 个容器(Vector)==> 依次装入链表的各个节点数据,vector1放比较小的数,vector2则放大的数。
3、vector.push_back():从尾部插入,即可把vector2 中的元素放入vector1 的尾部(即右侧)
4、遍历新容器,对原链表(head)进行重新赋值即可。
函数代码:
/** * 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) { vector<int>num1; vector<int>num2; ListNode*p=head; while(p){ if(p->val<x) num1.push_back(p->val); else{ num2.push_back(p->val); } p=p->next; } for(int x:num2){ num1.push_back(x); } ListNode*p2=head; for(auto m:num1){ if(!p2) return p2; p2->val=m; p2=p2->next; } return head; } };