leetcode:Partition List 【Java】

来源:互联网 发布:淘宝怎么异地发货 编辑:程序博客网 时间:2024/05/21 03:26

一、问题描述

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.

二、问题分析

建两个链表分别保存小于target的值和大于target的值。

在建新链表的过程中需要打断原链表中的链。

三、算法代码

/** * 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 lesser = null, lesserHead = null;        ListNode greater = null, greaterHeader = null;                ListNode cur = null;                if(head.val < x){            lesserHead = head;            lesser = head;            cur = head.next;            lesser.next = null;//打断原链表中的链        }else{            greaterHeader = head;            greater = head;            cur = head.next;            greater.next = null;//打断原链表中的链        }                while(cur != null){            if(cur.val < x){                if(lesserHead == null){                    lesserHead = cur;                    lesser = cur;                    cur = cur.next;                    lesser.next = null;//打断原链表中的链                }else{                    lesser.next = cur;                    lesser = lesser.next;                    cur = cur.next;                    lesser.next = null; //打断原链表中的链                }            }else{                if(greaterHeader == null){                    greaterHeader = cur;                    greater = cur;                    cur = cur.next;                    greater.next = null;//打断原链表中的链                }else{                    greater.next = cur;                    greater = greater.next;                    cur = cur.next;                    greater.next = null;//打断原链表中的链                }            }        }        if(lesserHead == null){            return greaterHeader;        }else{            lesser.next = greaterHeader;            return lesserHead;        }    }}


0 0
原创粉丝点击