leetcode 86. 分隔链表-java实现

题目所属分类

类似链表的快排

原题链接

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

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

在这里插入图片描述

代码案例:输入:head = [1,4,3,2,5,2], x = 3
输出:[1,2,2,4,3,5]

题解

在这里插入图片描述

/**
 * 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 before = new ListNode(0);
        ListNode after = new ListNode(0);
        ListNode p = before ;
        ListNode q = after ;
          for(ListNode a = head ; a != null ; a= a.next){
              if(a.val < x){
                  p = p.next = a ;
                  
              }else{
                  q =  q.next = a ;
                    
              }
          }
          p.next = after.next ;
          q.next = null ;
          return before.next;
    }
}

模拟

1、枚举整个链表,若当前元素小于 x,则加入到small链表中,若当前元素大于等于 x,则加入到big链表中,使得元素以x分类
2、将small的末尾元素指向big的开头元素
3、将big的末尾元素指向null
4、返回small.next

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode small = new ListNode(0);
        ListNode big = new ListNode(0);
        ListNode p = head;
        ListNode ps = small;
        ListNode pb = big;

        while(p != null)
        {
            if(p.val < x)
            {
                ps.next = p;
                ps = ps.next;
            }
            else
            {
                pb.next = p;
                pb = pb.next;
            }
            p = p.next;
        }
        pb.next = null;
        ps.next = big.next;

        return small.next;
    }
}

 
posted @ 2022-10-11 18:57  依嘫  阅读(32)  评论(0)    收藏  举报