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.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
[分析] 想到创建两个辅助链表就好办了,small链表存储小于x的节点,large链表存储大于x的节点,最后merge两个链表。
public class Solution {
public ListNode partition(ListNode head, int x) {
ListNode small = new ListNode(-1);
ListNode large = new ListNode(1);
ListNode pSmall = small;
ListNode pLarge = large;
ListNode curr = head;
while (curr != null) {
if (curr.val < x) {
pSmall.next = curr;
pSmall = pSmall.next;
} else {
pLarge.next = curr;
pLarge = pLarge.next;
}
curr = curr.next;
}
pLarge.next = null;
pSmall.next = large.next;
return small.next;
}
}
分享到:
相关推荐
javascript js_leetcode题解之86-partition-list.js
python python_leetcode题解之086_Partition_List
- **2.2.3 Partition List** - 按照给定值对链表进行分区。 - 实现思路:维护两个指针,分别指向小于和大于给定值的节点,最后连接两个部分。 - **2.2.4 Remove Duplicates from Sorted List** - 移除排序链表...
c语言基础 c语言_leetcode题解之0086_partition_list.zip
leetcode lintcode差异 leetcode-python 九章算法基础班 二分 题目 地址 153. Find ...List) LintCode 373. Partition Array by Odd and Even Mock Interview 题目 Solution Tag Dynamic Programming
* [Linked List](https://github.com/kamyu104/LeetCode#linked-list) * [Stack](https://github.com/kamyu104/LeetCode#stack) * [Queue](https://github.com/kamyu104/LeetCode#queue) * [Heap]...
reverse-linked-list-ii(Reverse a Sub-list) 141 环形链表 linked-list-cycle 142 环形链表 II linked-list-cycle-ii 143 重排链表 reorder-list 148 排序链表 sort-list 234 回文链表 palindrome-linked-list 双...
86.Partition List LeetCode 92.Reverse Linked List II LeetCode 138.Copy List with Random Pointer LeetCode 142.Linked List Cycle II(solve1) LeetCode 142.Linked List Cycle II(solve2) LeetCode 160....
list , Reference: Stack , Reference: , , Heap , Tree , , , DP/Greedy Reference: Reference: , Reference: , , , , , Recurrence Reference: Important NOTE!: 其中的Partition 是很常见的operation,标准做法是...
- **Partition List**:将链表按值分割成两个部分。 - **Add Two Numbers**:两个非负整数相加,结果存储在链表中。 - **Copy List with Random Pointer**:复制带有随机指针的链表。 8. **数学(Math)**: - ...
**1.8 Partition List (86)** - **问题描述**:给定一个链表和一个值 x,将链表中小于 x 的节点排在大于等于 x 的节点之前。 - **解题思路**: - 创建两个虚拟头节点分别记录小于 x 和大于等于 x 的节点。 - 遍历...
这段代码首先定义了一个`ListNode`类,然后实现了`partitionList`函数,按照上述策略进行链表分割。函数接受链表头节点作为输入,并返回两个新链表的头节点。 通过解决这个问题,你不仅可以提高对链表操作的理解,...
- **划分链表(Partition List)**: 将链表中所有小于x的节点移到所有大于或等于x的节点之前。 - **两数相加(Add Two Numbers)**: 给定两个非空链表代表两个非负整数,数字以逆序方式存储,每一位节点包含一个数字,将...