Leetcode: Partition List

來源:互聯網
上載者:User

標籤:des   style   class   blog   code   ext   

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.

Analysis: Linked List 慣用套路,Runner Technique(Two Pointers), 一些技巧就是:設定head的前置假節點prev,兩個pointer:current和runner都指到這個prev,然後進行判斷總是判斷 current.next 或者 runner.next. 這樣做按照我多次做類似題的經驗來說,是最方便省事不容易出錯的。這道題一次過。思路就是current 和 runner 一直移動直到找到 current.next >= x 為止,這裡就是後面小於x的元素將要插入的位置,current便停在這裡,指示這個位置,runner繼續往後面尋找,把每一個小於x的元素都插入到current.next 的位置。

 1 /** 2  * Definition for singly-linked list. 3  * public class ListNode { 4  *     int val; 5  *     ListNode next; 6  *     ListNode(int x) { 7  *         val = x; 8  *         next = null; 9  *     }10  * }11  */12 public class Solution {13     public ListNode partition(ListNode head, int x) {14         ListNode prev = new ListNode(-1);15         prev.next = head;16         ListNode current = prev;17         ListNode runner = prev;18         while (current.next != null && current.next.val < x) {19             current = current.next;20             runner = runner.next;21         }22         while (runner.next != null) {23             if (runner.next.val < x) {24                 ListNode temp = runner.next;25                 runner.next = runner.next.next;26                 temp.next = current.next;27                 current.next = temp;28                 current = current.next;29             }30             else runner = runner.next;31         }32         return prev.next;33     }34 }

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.