86. Partition List

一、题目

  1、审题

  2、分析

    给出一个整数链表,和一个目标数 x,将链表中节点值 < x 的节点放在值为 x 节点的左边,且保持链表原来的节点顺序。

二、解答

  1、思路:

    方法一、

      新建两个伪头结点,head1、head2,遍历链表节点:

      ①、若 val < x,则在 head1 后添加该节点

      ②、否则在 head2 后添加该节点

      ③、将head1 与 head2拼接,同时去除两个伪头结点。

public ListNode partition2(ListNode head, int x) {

        if(head == null || head.next == null)
            return head;
        
        ListNode fakeHead = new ListNode(0);
        fakeHead.next = head;
        ListNode pre = fakeHead;
        ListNode cur = head;
        ListNode next = new ListNode(x);
        ListNode head2 = next;
        
        while(cur != null) {
            if(cur.val < x) {
                pre.next = cur;
                pre = pre.next;
            }
            else {//if(cur.val >= x) {
                next.next = cur;
                next = next.next;
            }
            cur = cur.next;
        }
        next.next = null;
        pre.next = head2.next;
        return fakeHead.next;
    }
原文地址:https://www.cnblogs.com/skillking/p/9698756.html