题目: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.
分析:链表的特点在于不存在固定大小的存储区域,节点可以任意移动,插入。算法:遍历链表,分别插入两个新链表,一个小于x,一个大于等于x。然后把后者拼接在前者之后。
ListNode *partition(ListNode *head, int x) {
if(!head||!head->next) return head;
ListNode dummy_left(-1),dummy_right(-1);
ListNode *cur_left = &dummy_left, *cur_right = &dummy_right;
while(head)
{
if(head->val<x)
{
cur_left->next=head;
cur_left=head;
}
else
{
cur_right->next=head;
cur_right=head;
}
head=head->next;
}
cur_left->next=dummy_right.next;
cur_right->next= NULL;
return dummy_left.next;
}

本文详细介绍了如何使用链表实现将链表中的元素分为两部分,一部分包含所有小于给定值x的节点,另一部分包含所有大于等于x的节点。通过遍历链表并根据节点值进行分类,最终实现链表的高效分区。代码示例清晰展示了整个过程,包括初始化新链表、遍历原始链表并进行节点分类,以及最终连接两个新链表的方法。
330

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



