Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example:
Input: head = 1->4->3->2->5->2, x = 3 Output: 1->2->2->4->3->5
自己的想法链表元素的移动法要处理的细节比如两指针预先就位什么的很多很麻烦,结果:
Success
Runtime: 0 ms, faster than 100.00% of Java online submissions for Partition List.
Memory Usage: 36 MB, less than 100.00% of Java online submissions forPartition List.
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x){
if(head==null||head.next==null){return head;}
ListNode pre=head;
ListNode tar=head;
if(head.val>=x){
while(tar!=null&&tar.val>=x){pre=tar;tar=tar.next;}
if(tar==null){return head;}
pre.next=tar.next;
tar.next=head;
head=tar;
}
pre=head;
ListNode vic=head.next;
while(tar!=null&&tar.val<x){pre=tar;tar=tar.next;}
tar=pre;pre=head;
while(vic!=null&&vic.val<x){pre=vic;vic=vic.next;}
while(vic!=null&&vic.val>=x){pre=vic;vic=vic.next;}
while(vic!=null){
pre.next=vic.next;
vic.next=tar.next;
tar.next=vic;
tar=tar.next;
vic=pre.next;
//System.out.println(vic.val);
while(vic!=null&&vic.val>=x){
pre=vic;
vic=vic.next;
}
}
return head;
}
}
更简洁的方法是,设置两个指针移动和另两个head指针,即underhead和overhead,但是会进行多余的元素操作,没必要