加载中...
面试题 02.04-分割链表(Partition List LCCI)
发表于:2021-12-03 | 分类: 中等
字数统计: 416 | 阅读时长: 2分钟 | 阅读量:

原文链接: https://leetcode-cn.com/problems/partition-list-lcci

英文原文

Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list, the values of x only need to be after the elements less than x (see below). The partition element x can appear anywhere in the "right partition"; it does not need to appear between the left and right partitions.

Example:

Input: head = 3->5->8->5->10->2->1, x = 5
Output: 3->1->2->10->5->5->8

中文题目

给你一个链表的头节点 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.jpg

   if (!head || !head->next)  return head;
struct ListNode* h1 = (struct ListNode*)malloc(sizeof(struct ListNode)), *t1 = h1;
struct ListNode* h2 = (struct ListNode*)malloc(sizeof(struct ListNode)), *t2 = h2;
t1->next = NULL; t2->next = NULL;
while (head){
	if (head->val < x){
		t1->next = head;
		t1 = t1->next;
	}
	else{
		t2->next = head;
		t2 = t2->next;
	}
	head = head->next;
}
t1->next = h2->next;
t2->next = NULL;
return h1->next;

统计信息

通过次数 提交次数 AC比率
26835 41232 65.1%

提交历史

提交时间 提交结果 执行时间 内存消耗 语言
上一篇:
面试题 02.02-返回倒数第 k 个节点(Kth Node From End of List LCCI)
下一篇:
面试题 04.09-二叉搜索树序列(BST Sequences LCCI)
本文目录
本文目录