劃分鏈表
思路:
創建兩個鏈表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條評論