链表--分隔链表(leetcode86

题解

  • 不用修改原始链表(做题不要太死板,不一定非要在原始链表上进行修改)
  • 新建两个链表before和after
  • 在遍历原始链表的过程中,小于x的插入到before中,大于x的插入到after中
public ListNode partition(ListNode head, int x) {
        ListNode beforeHead = new ListNode(-1);
        ListNode afterHead = new ListNode(-1);
        ListNode before = beforeHead;
        ListNode after = afterHead;
        
        while (head != null){
            if(head.val < x){
                before.next = head;
                before = before.next;
            }else {
                after.next = head;
                after = after.next;
            }
            head = head.next;
        }

        after.next = null;
        
        before.next = afterHead.next;
        
        return beforeHead.next;
    }

时间复杂度:O(N),N为链表长度

空间复杂度:O(1),这个版本的代码是没有分配新空间的版本,只移动了原有的结点,因此没有使用任何额外空间。

另外,after.next = null是很有必要的,不能出现野指针


我自己写的答案是新建了结点的

public ListNode partition(ListNode head, int x) {
        ListNode beforeHead = new ListNode(-1);
        ListNode afterHead = new ListNode(-1);
        ListNode before = beforeHead;
        ListNode after = afterHead;

        while (head != null){
            if(head.val < x){
                before.next = new ListNode(head.val);
                before = before.next;
            }else {
                after.next = new ListNode(head.val);
                after = after.next;
            }
            head = head.next;
        }

        after.next = null;

        before.next = afterHead.next;

        return beforeHead.next;

    }
posted @ 2020-06-04 19:10  swifthao  阅读(114)  评论(0)    收藏  举报
Live2D