题解 | #链表分割#

链表分割

https://www.nowcoder.com/practice/0e27e0b064de4eacac178676ef9c9d70

import java.util.*;

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Partition {
    public ListNode partition(ListNode pHead, int x) {
        ListNode beforeHead = new ListNode(0);
        ListNode before = beforeHead;
        ListNode afterHead = new ListNode(0);
        ListNode after = afterHead;
        //遍历原始链表
        while (pHead != null) {
            if (pHead.val < x) {
                before.next = pHead;
                before = before.next;
            } else {
                after.next = pHead;
                after = after.next;
            }
            //移动到原始链表的下一个节点
            pHead = pHead.next;
        }
        //将after链表的末尾设置为null,防止成环
        after.next = null;
        before.next = afterHead.next;
        return beforeHead.next;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
03-15 10:59
已编辑
爱写代码的菜code...:哎,自己当时拿到字节offer的时候也在感叹终于拿到了,自己当时最想去的企业就是字节,结果还是阴差阳错去了鹅厂。祝uu一切顺利!!!
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务