LeetCode-86:Partition List

来源:互联网 发布:中世纪2优化9贴木耳 编辑:程序博客网 时间:2024/06/05 23:47

原题描述如下:

Given a linked list and a value x, partition it such that all nodes less thanx 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.

解题思路:

Java代码:

/**
 * 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 head1 = new ListNode(0);
        ListNode head2 = new ListNode(0);
        
        ListNode node1 = head1;
        ListNode node2 = head2;
        
        while(head != null){
            if(head.val < x){
                node1.next = head;
                node1 = node1.next;
            }else{
                node2.next = head;
                node2 = node2.next;
            }
            
            head = head.next;
        }
        
        if(node1 != head1){
            node1.next = head2.next;
            node2.next = null;
            return head1.next;
        }else{
            return head2.next;
        }
    }
}
0 0