Partition List

来源:互联网 发布:iphoneairplay连接mac 编辑:程序博客网 时间:2024/05/29 13:48

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的结点添加到新链表的尾部,然后在原链表中删除该结点,遍历完原链表之后,在新的链表的尾端加入原链表的头就可以了。

/** * 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) {        ListNode hr=new ListNode(-1);        ListNode current=head;        hr.next=head;        ListNode pre=hr;        ListNode less=new ListNode(-1);        ListNode tail=less;        while(current!=null)        {            if(current.val<x)               {                   tail.next=new ListNode(current.val);                   tail=tail.next;                   pre.next=current.next;                   current=current.next;                   continue;               }                        pre=current;            current=current.next;        }         tail.next=hr.next;        return less.next;    }}


0 0