(链表)21-分隔链表

/**
 * 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) {
        // 新建小于特定值x的链表
        ListNode small = new ListNode(0);
        // 申请小链表的遍历指针
        ListNode smallHead = small;
        // 新建大于特定值x的链表
        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;   
    }
}

 

posted @ 2023-11-21 22:37  StringBuilder  阅读(1)  评论(0编辑  收藏  举报