劃分鏈表,第1張

劃分鏈表,第2張

思路:

  創建兩個鏈表head1、head2 ,遍歷原鏈表,將大於 x 的節點鏈接至鏈表 head1,小於 x 的節點鏈接至鏈表 head2。

  再將鏈表 head1與 head2鏈接到一起即可。

importjava.util.*;
publicclass Solution {
    public ListNode partition (ListNode head, int x) {
        // write code here
        ListNode head1 = new ListNode(0), head2 = newListNode(0);
        ListNode cur1 = head1, cur2 =head2;
while(head != null) {
            if (head.val < x) {
                cur1.next = head;
                cur1 = cur1.next;
            } else {
                cur2.next = head;
                cur2 = cur2.next;
            }
            head = head.next;
        }
        cur1.next = head2.next;
        cur2.next =null;
return head1.next;
    }
}

生活常識_百科知識_各類知識大全»劃分鏈表

0條評論

    發表評論

    提供最優質的資源集郃

    立即查看了解詳情