力扣Java版个人代码分享-链表篇(删除排序链表中的重复元素||)

86. 分隔链表

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。

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

例子

输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5

代码

    public ListNode partition(ListNode head, int x) {
    
    
        ListNode temp = new ListNode();
        ListNode l1 = new ListNode();
        ListNode l2 = new ListNode();
        ListNode l3 = new ListNode();
        l3 = l1;
        temp.next = head;
        if(head == null){
    
    
            return head;
        }
        if(head.next == null){
    
    
            return head;
        }
        head = l2;
        while(temp.next != null){
    
    
            if(temp.next.val >= x){
    
    
                l1.next = temp.next;
                l1 = l1.next;
            }else{
    
    
                l2.next = temp.next;
                l2 = l2.next;
            }
            temp = temp.next;
        }
        l1.next = null;
        if(l3.next != null) {
    
    
            l3.val = l3.next.val;
            l3.next = l3.next.next;
            l2.next = l3;
        }else{
    
    
            return head.next;
        }
        return head.next;
    }

注意事项

注意空指针异常

待优化

猜你喜欢

转载自blog.csdn.net/northern0407/article/details/108273157