86. 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.

Solution:two pointers

思路:创建两个新list,将原list根据和x相比的大小剥离出来分别放到这两个list中,再连接
Time Complexity: O(N) Space Complexity: O(1)

Solution Code:

class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode dummy1 = new ListNode(0), dummy2 = new ListNode(0);
        ListNode curr1 = dummy1, curr2 = dummy2;
        while (head != null){
            if (head.val < x) {
                curr1.next = head;
                curr1 = head;
            }else {
                curr2.next = head;
                curr2 = head;
            }
            head = head.next;
        }
        curr2.next = null;
        curr1.next = dummy2.next;
        return dummy1.next;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,767评论 0 33
  • 一切都还是起点,加油吧
    步积阅读 286评论 2 1
  • “那个女生有伞为什么不打?”“因为她认命,至此认命。” “为什么她不表现得难过些?”“因为不需要表现得忧伤,让别人...
    d0cf46af0d87阅读 633评论 4 5
  • 熬制了两个小时的药膳汤水,烧的滚烫。缓缓倒入实木抠成的盆子里,伴随着中药的奇异香味。缓缓把脚担在盆壁,盖上厚厚的毛...
    彩蛋旅行阅读 515评论 2 51
  • 落笔会成花 彩铅画,普通的笔却绘出了夏日的味道!是薄荷,是青草? 在浅浅的黄昏中,碰见了四叶草,该是夏日多么幸运的...
    为为道来阅读 273评论 0 4