leetcode_middle_91_86. Partition List

来源:互联网 发布:怎么用数据透视表求和 编辑:程序博客网 时间:2024/06/14 05:06

题意:

给一个单链表和一个数值,将链表中小于这个数的结点放前面,大于等于这个数的结点放后面,并保持相对顺序不变,构造新链表。


分析:

直接一个链表装大的,一个装小的,连起来就是了。

/** * 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 smallHead = new ListNode(0);        ListNode small = smallHead;        ListNode bigHead = new ListNode(0);        ListNode big = bigHead;        while(head != null){            if(head.val < x){                small.next = head;                small = small.next;            }else{                big.next = head;                big = big.next;            }            head = head.next;        }        big.next = null;        small.next = bigHead.next;        return smallHead.next;    }}

注意:

big.next = null;

先前忘了这一句,超时。链表就是要注意处理好一头一尾。


0 0
原创粉丝点击