Partition List

来源:互联网 发布:经销商车销软件 编辑:程序博客网 时间:2024/05/22 11:31

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.


思路:

这道题要求将一个链表重新排列,其中元素小于k的在前面,大于等于k的在后面。

如果在原链表上操作会把原链表搞的支零破碎,非常麻烦。如果能过想到构造出两个新的链表,那题目的难度会降低很多。

一个链表用来存储小于k的元素,另一个链表用于存储大于k的元素,在将所有元素存储完毕之后,将两个链表拼接在一起就大功告成了。


public class PartitionList {    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 cur1 = dummy1;        ListNode cur2 = dummy2;        while(head != null) {        if(head.val < x) {        cur1.next = new ListNode(head.val);        cur1 = cur1.next;        } else {        cur2.next = new ListNode(head.val);        cur2 = cur2.next;        }        head = head.next;        }    cur1.next = dummy2.next;    return dummy1.next;    }}




原创粉丝点击