86. 分隔链表

/**
 * 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) {
        ListNode dummy1 = new ListNode();
        ListNode dummy2 = new ListNode();
        ListNode cur = head;
        ListNode node1 = dummy1;
        ListNode node2 = dummy2;
        while (cur != null) {
            if (cur.val < x) {
                node1.next = cur;
                cur = cur.next;
                node1 = node1.next;
                node1.next = null;
            } else {
                node2.next = cur;
                cur = cur.next;
                node2 = node2.next;
                node2.next = null;
            }
            
        }
        node1.next = dummy2.next;
        return dummy1.next;
    }
}
上一篇:


下一篇:JAVA Leetcode232. 用栈实现队列