FTPrep, 86 Partition List

来源:互联网 发布:法师雾化器做芯数据 编辑:程序博客网 时间:2024/06/06 09:27

这道题,我一开始想到的就是 array形式的 partition,通过swap来交换。于是开始傻傻分不清的 开始想在list 中怎么swap。只能说明,要么天赋太浅,要么不够用心,还没体会到array和list的本质差异,以及在这个本质差异上带来的哪些的操作的是便利和不便利。

这道题用 老链头删和新链尾插就很好实现。头删需要2个指针,一个标记currNode,一个维护headNode。同样两个node,一个dummy,维护整条链,一个维护尾巴。最终两条链会链接起来。

这道题要和array的题目一起记忆。TODO:array中的partition是quickSort的核心引擎,非常重要,这里的话给出了一个链条,联系两道题。

代码:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */class Solution {    public ListNode partition(ListNode head, int x) {        if(head==null) return head;        ListNode dummy1 = new ListNode(-1);        ListNode curr1 = dummy1;        ListNode dummy2 = new ListNode(-1);        ListNode curr2 = dummy2;        while(head!=null){            if(head.val<x){                curr1.next=head;                curr1=curr1.next;                head=head.next; // this step and the following step cannot be switched.                curr1.next=null;            }else{                curr2.next=head;                curr2=curr2.next;                head=head.next;                curr2.next=null;            }        }            curr1.next=dummy2.next;            return dummy1.next;    }}