LeetCode-分隔链表

118 阅读1分钟

算法记录

LeetCode 题目:

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

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


说明

一、题目

  输入:head = [1,4,3,2,5,2], x = 3   输出:[1,2,2,4,3,5]

二、分析

  • 不改变相对顺序,只需要重头开始遍历链表,然后将大于和小于的分别组成一个单独链表。
  • 最后将两个链表进行连接返回即可。
class Solution {
    public ListNode partition(ListNode head, int x) {
        if(head == null) return head;
        ListNode one = new ListNode(), two = new ListNode();
        ListNode o = one, t = two;
        while(head != null) {
            if(head.val >= x) {
                o.next = head;
                o = o.next;
            } else {
                t.next = head;
                t = t.next;
            }
            head = head.next;
        }
        o.next = null;
        t.next = one.next;
        return two.next;
    }
}

总结

熟悉链表的遍历和连接使用。