思路: 創(chuàng)建兩個鏈表 head1、head2 ,遍歷原鏈表,將大于 x 的節(jié)點鏈接至鏈表 head1,小于 x 的節(jié)點鏈接至鏈表 head2。 再將鏈表 head1與 head2鏈接到一起即可。 import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head ListNode類 * @param x int整型 * @return ListNode類 */ public ListNode partition (ListNode head, int x) { // write code here ListNode head1 = new ListNode(0), head2 = new ListNode(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; } } |
|