前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode面试题 02.04. 分割链表

LeetCode面试题 02.04. 分割链表

作者头像
周杰伦本人
发布2022-10-25 17:23:22
1020
发布2022-10-25 17:23:22
举报
文章被收录于专栏:同步文章

//给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。 // // 你应当 保留 两个分区中每个节点的初始相对位置。 // // // // 示例 1: // // //输入:head = [1,4,3,2,5,2], x = 3 //输出:[1,2,2,4,3,5] // // // 示例 2: // // //输入:head = [2,1], x = 2 //输出:[1,2] // // // // // 提示: // // // 链表中节点的数目在范围 [0, 200] 内 // -100 <= Node.val <= 100 // -200 <= x <= 200 // // Related Topics 链表 双指针 // 👍 65 👎 0

//leetcode submit region begin(Prohibit modification and deletion) /**

Definition for singly-linked list.

public class ListNode {

代码语言:javascript
复制
int val;
代码语言:javascript
复制
ListNode next;
代码语言:javascript
复制
ListNode(int x) { val = x; }

} */ 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; }

代码语言:javascript
复制
 large.next =null;
 small.next = largeHead.next;

 return smallHead.next;

} } //leetcode submit region end(Prohibit modification and deletion)

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-07-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档