以x为基准分割链表小于x的结点排在大于等于x的结点之前原顺序不变

编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前且原顺序不变

思维逻辑图如下:
先将<x的数字排成一个新链表,将>x的数字拍成一个新链表,最后将这两个链表连在一起即可。
bs:<x新链表的头(b start);
be:<x新链表的尾(b end);
as:>x新链表的头(b start);
ae:>x新链表的尾(b end);
将两个新链表连在一起只需让be指向as即可。
在这里插入图片描述

代码如下:

public ListNode partition(int x) {
        ListNode cur = this.head;
        ListNode bs = null;
        ListNode be = null;
        ListNode as = null;
        ListNode ae = null;
        while(cur != null) {
            if(cur.data < x) {
                //判断是不是第一次插入
                if(bs == null) {
                    bs = cur;
                    be = bs;
                }else {
                    be.next = cur;
                    be = be.next;//be = cur;
                }
            }else {
                //判断是不是第一次插入
                if(as == null) {
                    as = cur;
                    ae = cur;
                }else {
                    ae.next = cur;
                    ae = ae.next;//ae = cur;
                }
            }
            cur = cur.next;
        }
        if(bs == null){
            return as;
        }
        be.next = as;
        if(as != null) {
            ae.next = null;
        }
        return bs;
    }
发布了43 篇原创文章 · 获赞 41 · 访问量 1790

猜你喜欢

转载自blog.csdn.net/weixin_45662626/article/details/103097075