[LeetCode][Java] Partition List

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.