题解 | #链表分割#

链表分割

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

全部评论

相关推荐

09-02 11:14
已编辑
四川大学 Java
吴offer选手:这种面试是最烦的,学不到东西,然后还被挂的莫名其妙。之前看到一种说法是面试官如果不想要你了,就会问一些很简单的问题,防止你举报他
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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