1 Star 0 Fork 0

ZechariahZheng / blog文档

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
LeetCode_86 分隔链表.md 1.26 KB
一键复制 编辑 原始数据 按行查看 历史
ZechariahZheng 提交于 2020-01-03 09:06 . LeetCode_86 分隔链表

LeetCode_86 分隔链表

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

示例:

输入: head = 1->4->3->2->5->2, x = 3 输出: 1->2->2->4->3->5

思路:使用两个链表,其中一个链表保存小于x的值,另一个链表保存大于等于x的值,最后将两个链表拼接即可

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode min = new ListNode(0);
        ListNode max = new ListNode(0);
        ListNode tmp2 = min;
        ListNode tmp1 = max;
        
        while (head != null) {
            if (head.val >= x) {
                tmp1.next = head;
                head = head.next;
                tmp1 = tmp1.next;
                tmp1.next = null;
            } else {
                tmp2.next = head;
                head = head.next;
                tmp2 = tmp2.next;
                tmp2.next = null;
            }
        }
        tmp2.next = max.next;
        return min.next;
    }
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/ZechariahZheng/blog_document.git
git@gitee.com:ZechariahZheng/blog_document.git
ZechariahZheng
blog_document
blog文档
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891