標籤:leetcode java partition list
題目:
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.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
題意:
給定一個鏈表和一個值x,分割鏈表使得比x小的節點都在大於或等於x的節點的前面。
你需要分別在這兩個分割的部分中保持節點原始的相對順序。
比如,
給定1->4->3->2->5->2 和 x =3 ,
返回1->2->2->4->3->5.
演算法分析:
* 分兩次遍曆單鏈表
* 一次記錄比目標值小的所有值
* 一次記錄比目標值大的所有值
* 最終將這兩個記錄合并
* 得到最終的結果
AC代碼:
<span style="font-family:Microsoft YaHei;font-size:12px;">public class Solution { public ListNode partition(ListNode head, int x) { if(head==null) return head; ListNode fhead = head; ListNode shead = head; ListNode res=new ListNode(0) ; ListNode fres=res; while(fhead!=null) { if(fhead.val<x) { res.next= new ListNode(fhead.val); res=res.next; } fhead=fhead.next; } while(shead!=null) { if(shead.val>=x) { res.next= new ListNode(shead.val); res=res.next; }shead=shead.next; } return fres.next; }}</span>
著作權聲明:本文為博主原創文章,轉載註明出處
[LeetCode][Java] Partition List