划分链表
思路:
创建两个链表 head1、head2 ,遍历原链表,将大于 x 的节点链接至链表 head1,小于 x 的节点链接至链表 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; } }