LeetCode面试题:分隔链表

发布时间:2023-04-25 11:00:11

  1.简述:

  给你一个链表的头节点 head 和一个特定值 x ,请将链表分开,使所有链表都可以分开 小于 x 所有的节点都出现了 大于或等于 x 在节点之前。

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

  示例 1:

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

  输出:[1,2,2,4,3]

  示例 2:

  输入:head = [2,1], x = 2

  输出:[1,2]

  2.实现代码:class Solution { public ListNode partition(ListNode head, int x) { ListNode small = new ListNode(0); ListNode smallHead = small; ListNode large = new ListNode(0); ListNode largeHead = large; while (head != null) { if (head.val < x) { small.next = head; small = small.next; } else { large.next = head; large = large.next; } head = head.next; } large.next = null; small.next = largeHead.next; return smallHead.next; }}

上一篇 类的定义与对象的创建使用
下一篇 LeetCode程序员面试金典:搜索插入位置

文章素材均来源于网络,如有侵权,请联系管理员删除。

标签: Java教程Java基础Java编程技巧面试题Java面试题