86. Partition List

来源:互联网 发布:淘宝上的毕业证真的吗 编辑:程序博客网 时间:2024/06/03 18:33

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.

Subscribe to see which companies asked this question.

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode partition(ListNode head, int x) {        ListNode newhead = new ListNode(0);ListNode re = newhead;ListNode temp = head;while (temp != null && temp.val < x) {newhead.next = temp;newhead = newhead.next;temp = temp.next;}if (temp == null)return re.next;ListNode store = temp;ListNode pre = temp;temp = temp.next;while (temp != null) {if (temp.val < x) {pre.next = temp.next;newhead.next = temp;newhead = newhead.next;temp = temp.next;} else {pre = temp;temp = temp.next;}}newhead.next = store;return re.next;    }}


0 0
原创粉丝点击