分隔链表-LeetCode

题目描述:

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

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

示例:

输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5

解题思路:

  1. 创建两个新链表,一个存放原链表中小于x的数据,另一个存放原链表中大于或等于x的数据。
  2. 将两个链表拼接起来。

代码实现:

class Solution {
    public ListNode partition(ListNode head, int x) {
        if (head == null || head.next == null) {
            return head;
        }
        //存放数值小于x的链表
        ListNode newNode1 = new ListNode(-1);
        //存放数值大于等于x的链表
        ListNode newNode2 = new ListNode(-1);
        ListNode temp1 = newNode1;
        ListNode temp2 = newNode2;
        while (head != null) {
            if (head.val < x) {
                temp1.next = new ListNode(head.val);
                temp1 = temp1.next;
            }else {
                temp2.next = new ListNode(head.val);
                temp2 = temp2.next;
            }
            
            head = head.next;
        }
        //将两个链表拼接起来。
        temp1.next = newNode2.next;
        return newNode1.next;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43573824/article/details/88802992