题目描述:
给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。
你应当 保留 两个分区中每个节点的初始相对位置。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/partition-list
解题核心:创建临时头结点
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode less_head(0);//创建一个临时头结点!,类型就是listnode而不是listnode*
ListNode* less_ptr=&less_head;//让ptr指向结点,应赋结点的地址;这里才是指向结点的类型listnode*
//less_ptr->next=nullptr;
ListNode more_head(0);
ListNode* more_ptr=&more_head;
//more_ptr->next=nul