LeetCode - Partition List

https://leetcode.com/problems/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.

这道题还是比较简单的,就是分成两个子list,一个里面的值都小于x,一个里面的值都大于等于x,然后再把两个List连起来,注意,第二个list的最后一个node,它本身的next可能是指向非null节点的,要把它设置成null,不然这个list就有circle了。

    public ListNode partition(ListNode head, int x) {
        if(head==null || head.next==null) return head;
        ListNode dummy1 = new ListNode(0);
        ListNode dummy2 = new ListNode(0);
        ListNode pre1 = dummy1;
        ListNode pre2 = dummy2;
        while(head!=null){
            if(head.val<x){
                pre1.next = head;
                pre1 = pre1.next;
            }
            else{
                pre2.next = head;
                pre2 = pre2.next;
            }
            head = head.next;
        }
        pre1.next = dummy2.next;
        pre2.next = null;
        return dummy1.next;
    }

我看leetcode给的tag里面还有two pointer的解法,应该是一个指针扫描,一个指针前面的node全部是比x小的,然后当遇到比x小的,就把这个节点移到第二个指针所在的位置。因为这里没说不能改变node value,所以直接交换值就可以了。或者delete再insert这个node。这种方法还是比较麻烦的哈,容易错。而且这种方法不能保持原有的顺序了。

Input: {2,3,1}, 2
Output: {1,3,2}
Expected: {1,2,3}

    public ListNode partition(ListNode head, int x) {
        if(head==null || head.next==null) return head;
        ListNode traverse = head;
        ListNode less = head;
        while(traverse!=null){
            if(traverse.val < x){
                int tmp = less.val;
                less.val = traverse.val;
                traverse.val = tmp;
                less = less.next;
            }
            traverse = traverse.next;
        }
        return head;
    }

所以还是第一种方法好哈。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值