Partition list

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.

Example
Given 1->4->3->2->5->2->null and x = 3, return 1->2->2->4->3->5->null.

注意:
分开两个大小链表来连接大小的节点,节点连接到大小链表之后,不需要将其的next 更新为 null,到最后设置 big 最后一个的 next 为 null 即可。

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @param x: an integer
     * @return: a ListNode 
     */
    public ListNode partition(ListNode head, int x) {
        // write your code here
        ListNode dummy1 = new ListNode(0);
        ListNode smallLast = dummy1;
        ListNode dummy2 = new ListNode(0);
        ListNode bigLast = dummy2;
        while (head != null) {
            if (head.val < x) {
                smallLast.next = head;
                smallLast = smallLast.next;
            } else {
                bigLast.next = head;
                bigLast = bigLast.next;
            }
            head = head.next;
        }
        smallLast.next = dummy2.next;
        bigLast.next = null;
        return dummy1.next;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 过完年了,我的花花草草也长了不少,想想也只有它们才会长久的陪伴着你,愉悦你,不会惹你生气。 长寿华全长...
    苍山暮雪阅读 658评论 0 1
  • 人一辈子要走过很多路,或崎岖,或坦途,或曲折,或荆棘……当你走过去,回望也会怀念路途的艰辛与无奈,可是路总要走过去...
    samsonic阅读 1,251评论 0 2