程序笔记   发布时间:2022-07-12  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了86. 分隔链表大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

Example 1:

86. 分隔链表

Input: head = [1,4,3,2,5,2], x = 3
Output: [1,2,2,4,3,5]

Example 2:

Input: head = [2,1], x = 2
Output: [1,2]

ConsTraints:

  • the number of nodes in the list is in the range [0, 200].
  • -100 <= Node.val <= 100
  • -200 <= x <= 200

分隔链表。

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

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

 

思路:申请小于和大于的头尾节点,让其按要求增长成小于和大于等于的链表,最后小于的尾(如果有的话)去联接大于等于的头

在比较时让当前节点独立出来

  ListNode cur=head;
  cur.next=null;

 

class Solution {
    public ListNode partition(ListNode head, int X) {
        if(head==null||head.next==null){
            return head;
        }
        ListNode sH=null;
        ListNode sT=null;
        ListNode bH=null;
        ListNode bT=null;
       
        while(head!=null){
            ListNode next=head.next;
            ListNode cur=head;
            //和head链表断联
            cur.next=null;
            if(cur.val<X){
                if(sH==null){
                    sH=cur;
                    sT=cur;
                }else{
                    sT.next=cur;
                    sT=cur;
                }
            }else{
                if(bH==null){
                    bH=cur;
                    bT=cur;
                }else{
                    //注意这里指针的变换
                    bT.next=cur;
                    bT=cur;
                }
            }
            head=next;
        }

     if(sT==null){
         return bH;
     }else{
         sT.next=bH;
         return sH;
     }


    }
}
@H_607_62@

  

 

 

第二种解法,利用辅助节点,让小于和大于等于的处于相同的处理

class Solution {
    public ListNode partition(ListNode head, int X) {
        // corner case
        if (head == null || head.next == null) {
            return head;
        }

        // normal case
        ListNode p = new ListNode(0);
        ListNode pHead = p;
        ListNode q = new ListNode(0);
        ListNode qHead = q;
        while (head != null) {
            // < x成一组
            if (head.val < X) {
                p.next = head;
                p = p.next;
            }
            // >= x成一组
            else {
                q.next = head;
                q = q.next;
            }
            head = head.next;
        }
        p.next = qHead.next;
        q.next = null;
        return pHead.next;
    }
}
@H_607_62@

  

大佬总结

以上是大佬教程为你收集整理的86. 分隔链表全部内容,希望文章能够帮你解决86. 分隔链表所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。