86. 分隔链表

题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

 

解题思路:读了几遍才看懂什么意思。。。使用双指针进行解题,一趟遍历即可完成调整。时间复杂度为O(n)

  1. 如果head ==null || head.next == null,无需调整位置,直接返回head即可
  2. 设置一个哑元节点dumpy,令dumpy.next = head
  3. 双指针:
    1. prev:已经调整过位置的节点中小于x 的节点中最后一个节点,初始值指向dumpy,即头节点的前驱
    2. end:已经调整过位置的节点中大于等于x的节点中的最后一个节点,初始值为null
  4. 从前向后遍历链表,依次调整每一个节点的位置:
    1. 如果当前节点值比x小,就将其插入到pre节点后面,更新pre为新插入的节点
    2. 如果当前节点大于等于x,就将其插入到end节点后面,更新end=end.next

AC代码:

/**
 * 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) {
        if (head == null||head.next==null) {
            return head;
        }
        ListNode dumpy = new ListNode();
        dumpy.next = head;
        ListNode pre = dumpy;
        ListNode end = null;

        while (head != null) {
            if (head.val < x) {
                ListNode tem = head;
                head = head.next;
                if (pre.next!=tem){
                    tem.next = pre.next;
                }
                pre.next = tem;
                pre = pre.next;

            } else {
                if (end==null){
                    pre.next = head;
                    end= head;
                    head=head.next;
                }else {
                    end.next = head;
                    end=end.next;
                    head=head.next;

                }
            }
        }
        if (end!=null){
            end.next=null;
        }

        return dumpy.next;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值