Split list java

Given a linked list and a specific value x, please separate the linked list so that all nodes less than x appear before nodes greater than or equal to x.

You should keep the initial relative position of each node in the two partitions.

Example:

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5

Source: LeetCode
Link: https://leetcode-cn.com/problems/partition-list
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    //直观来说我们只需维护两个链表 \textit{small}small 和 \textit{large}large 即可,\textit{small}small 链表按顺序存储所有小于 xx 的节点,\textit{large}large 链表按顺序存储所有大于等于 xx 的节点。遍历完原链表后,我们只要将 \textit{small}small 链表尾节点指向 \textit{large}large 链表的头节点即能完成对链表的分隔。
    public ListNode partition(ListNode head, int x) {
    
    
        ListNode small = new ListNode(0);
        ListNode smallHead = small;
        ListNode large = new ListNode(0);
        ListNode largeHead = large;
        while(head!=null)
        {
    
    
            if(head.val<x){
    
    
                small.next = head;
                small = small.next;
            }else{
    
    
                large.next = head;
                large = large.next;
            }
            head = head.next;
        }
        large.next = null;
        small.next = largeHead.next;
        return smallHead.next;
    }
}

Guess you like

Origin blog.csdn.net/weixin_43824233/article/details/112134473