[LeetCode]Partition List, 解题报告

2014-11-24 08:09:06 · 作者: · 浏览: 0

题目

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.

思路

题意:这道题目就是在不改变链表原来顺序的情况下,将大于x的节点移到后面,小于x的节点移到前面
解法:我们可以构建两个链表,一个链表存放所有小于x的节点,另一个链表存放所有大于x的节点,然后连接两个链表即可

AC代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode smaller, bigger, tmps, tmpb;

        smaller = new ListNode(0);
        tmps = smaller;

        bigger = new ListNode(0);
        tmpb = bigger;

        while (head != null) {
            if (head.val < x) {
                tmps.next = head;
                tmps = head;
            } else {
                tmpb.next = head;
                tmpb = head;
            }

            head = head.next;
        }

        tmpb.next = null;
        tmps.next = bigger.next;

        return smaller.next;
    }
}