Leetcode - Partition List.

来源:互联网 发布:win10没有解压软件 编辑:程序博客网 时间:2024/05/22 15:39

https://oj.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.


public ListNode partition(ListNode head, int x)


这一题的解题思路很简单,就是根据x值构造两个list,一个list小于x,另一个list大于等于x即可,用一个tmp指针一路往下扫一路构建。然后连在一起就可以了。需要注意的不过是一些边界条件,譬如说x大于或者小于链表上的所有数。

    public ListNode partition(ListNode head, int x) {        ListNode smallHead = null, smalltmp = null, largeHead = null, largetmp = null, tmp = head;        while(tmp != null){            if(tmp.val < x){                if(smallHead == null){                    smallHead = tmp;                    smalltmp = smallHead;                }else{                    smalltmp.next = tmp;                    smalltmp = smalltmp.next;                }            }else{                if(largeHead == null){                    largeHead = tmp;                    largetmp = largeHead;                }else{                    largetmp.next = tmp;                    largetmp =largetmp.next;                }            }            tmp = tmp.next;            if(smalltmp != null)smalltmp.next = null;            if(largetmp != null)largetmp.next = null;        }        if(smalltmp != null)smalltmp.next = largeHead;        return smallHead == null ? largeHead : smallHead;


0 0