leetcode 86分隔链表

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

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

示例 1:

image
输入:head = [1,4,3,2,5,2], x = 3
输出:[1,2,2,4,3,5]
示例 2:
输入:head = [2,1], x = 2
输出:[1,2]
提示:

链表中节点的数目在范围 [0, 200] 内
-100 <= Node.val <= 100
-200 <= x <= 200

链接:https://leetcode-cn.com/problems/partition-list

将链表拆成两个然后重新组合
大于等于x的一个链表,小于x的一个链表

/**
 * 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)
        {
            return head;
        }

        ListNode pre=new ListNode();
        pre.next=head;
        ListNode cur=head;
        ListNode smaller=new ListNode();
        ListNode smllerPointer=smaller;
        ListNode bigger=new ListNode();
        ListNode biggerPointer=bigger;
        while (cur!=null)
        {
            if(cur.val<x)
            {
                smllerPointer.next=cur;
                pre.next=cur.next;
                cur.next=null;
                smllerPointer=cur;
            }else
            {
                biggerPointer.next=cur;
                pre.next=cur.next;
                cur.next=null;
                biggerPointer=cur;

            }

            cur=pre.next;
        }
        smllerPointer.next=bigger.next;
        pre.next=smaller.next;
        return pre.next;
    }
}

优化版本

/**
 * 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)
        {
            return head;
        }
        ListNode smaller=new ListNode();
        ListNode smallPointer=smaller;
        ListNode bigger=new ListNode();
        ListNode biggerPointer=bigger;
        //要拆掉原来的链表
        while (head!=null)
        {
            if(head.val<x)
            {
                smallPointer.next=head;
                smallPointer=smallPointer.next;
            }else
            {
                biggerPointer.next=head;
                biggerPointer=biggerPointer.next;
            }
            head=head.next;
        }
        biggerPointer.next=null;//在做链表题目的时候完成链表一定要切断所有联系,表尾置空
        smallPointer.next=null;
        smallPointer.next=bigger.next;
        return smaller.next;
    }
}
posted @ 2021-08-30 10:18  LiangLiangAA  阅读(23)  评论(0编辑  收藏  举报
theme: { name: 'geek', avatar: '', headerBackground: '' // ... },