链表 - 将大于某一个值的节点全部放在右边、小于该值的放在左边
给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。
你应当 保留 两个分区中每个节点的初始相对位置。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/partition-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode partition(ListNode head, int x) { ListNode dummyHead1 = new ListNode(0); ListNode dummyHead2 = new ListNode(0); ListNode cur1 = dummyHead1; ListNode cur2 = dummyHead2; while (head != null) { if (head.val < x) { cur1.next = head; head = head.next; cur1 = cur1.next; cur1.next = null; } else { cur2.next = head; head = head.next; cur2 = cur2.next; cur2.next = null; } } cur1.next = dummyHead2.next; return dummyHead1.next; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步