题目描述

代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}//这玩意算是结构体的构造函数了,这一点要注意
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {//核心思想是用四个指针
ListNode* small = new ListNode(0);
ListNode* smallHead = small;
ListNode* large = new ListNode(0);
ListNode* largeHead = large;
while (head != nullptr) {
if (head->val < x) {
small->next = head;
small = small->next;
} else {
large->next = head;
large = large->next;
}
head = head->next;
}
large->next = nullptr;
small->next = largeHead->next;
return smallHead->next;
}
};
该博客介绍了一个C++代码实现,用于将给定的单链表中的所有节点根据其值是否小于某个指定的整数x进行分区。代码中定义了一个`ListNode`结构体,并在`Solution`类中定义了一个`partition`方法,通过四个指针有效地将小于x的节点和大于等于x的节点分开。此方法对于链表操作和数值比较有很好的演示作用。
760

被折叠的 条评论
为什么被折叠?



