LeetCode 086 Partition List

来源:互联网 发布:sqlserver 创建临时表 编辑:程序博客网 时间:2024/06/17 17:49

题目


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.

思路


1 遍历原链表,根据大小分别放入制作成另外两个链表。

2 遍历完成后,注意对两个链表的连接和结尾处理。


代码


public ListNode partition(ListNode head, int x) {        if(head == null){            return null;        }        ListNode dummy1 = new ListNode(Integer.MIN_VALUE);        ListNode dummy2 = new ListNode(Integer.MAX_VALUE);        ListNode cur1 = dummy1;        ListNode cur2 = dummy2;                ListNode cur = head;        while(cur!=null){            if(cur.val>=x){                cur2.next = cur;                cur2 = cur2.next;            }            else{                cur1.next = cur;                cur1 = cur1.next;            }            cur = cur.next;        }        cur1.next = dummy2.next;        cur2.next = null;        return dummy1.next;    }





0 0
原创粉丝点击