当前位置:首页 > 开发 > 编程语言 > 编程 > 正文

Partition List

发表于: 2015-07-08   作者:hcx2013   来源:转载   浏览:
摘要: 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 th

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.

 

/**
 * 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) {
        if (head==null || head.next==null) {
        	return head;
        }
        ListNode small = new ListNode(-1);
        ListNode big = new ListNode(-1);
        ListNode samllH = small;
        ListNode bigH = big;
        while (head != null) {
        	if (head.val < x) {
        		small.next = head;
        		small = small.next;
        	} else {
        		big.next = head;
        		big = big.next;
        	}
        	head = head.next;
        }
        big.next = null;
        small.next = bigH.next;
        return samllH.next;
    }
}

 

Partition List

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号