Partition List

来源:互联网 发布:淘宝苏宁易购怎么退货 编辑:程序博客网 时间:2024/06/08 02:11

Partition List

 Total Accepted: 4859 Total Submissions: 18717My Submissions

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大的链表,最后吧两个链表链接起来。


    public static ListNode partition(ListNode head, int x){        ListNode small = new ListNode(0);        ListNode temp = small;        ListNode big = new ListNode(0);        big.next = head;        head = big;        while(head.next!=null){            if(head.next.val < x){                temp.next = head.next;                head.next = head.next.next;                temp = temp.next;                continue;            }            head = head.next;        }        temp.next = big.next;        return small.next;    }









0 0
原创粉丝点击