leetcode86. Partition List

題目要求

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的值放在後面,移動的過程當中不改變數字之間的相對順序。node

思路一:移動節點

該思路須要咱們記錄3個節點。當前節點的前一個節點currentPrev,插入位置的前一個節點prev,以及記錄初始位置的節點start。當發現一個須要交換的節點時,先得到這個節點,而後將currentPrev指向節點的後一個節點。以後將當前的節點插入到prev以後。代碼以下:面試

public ListNode partition(ListNode head, int x) {
        if(head==null || head.next==null){
            return head;
        }
        ListNode start = new ListNode(0);
        ListNode prev = new ListNode(0);
        ListNode currentPrev = new ListNode(0);
        start.next = prev;
        prev.next = head;
        currentPrev.next = head;
        while(currentPrev.next!=null && currentPrev.next.val<x){
            currentPrev = currentPrev.next;
            prev = prev.next;
        }
        while(currentPrev!=null && currentPrev.next!=null){
            int val = currentPrev.next.val;
            if(val < x){
                ListNode temp = currentPrev.next;
                currentPrev.next = currentPrev.next.next;
                temp.next = prev.next;
                prev.next = temp;
                prev = prev.next;    
            }else{
                currentPrev = currentPrev.next;
            }
        }
        return start.next.next;
    }

思路二:使用兩個鏈表

咱們設置兩個頭指針當作兩個鏈表,當遇到的數值小於x,則加入第一個鏈表,不然加入第二個鏈表。最後將兩個鏈表鏈接。代碼相比於第一種更加清晰一些。微信

public ListNode partition2(ListNode head, int x) {
        if (head == null || head.next == null) return head;
        
        ListNode dummy1 = new ListNode(0);
        ListNode dummy2 = new ListNode(0);
        ListNode curr = head, first = dummy1, second = dummy2;
        while (curr != null) {
            if (curr.val < x) {
                first.next = curr;
                first = first.next;
            } else {
                second.next = curr;
                second = second.next;
            }
            curr = curr.next;
        }
        first.next = dummy2.next;
        second.next = null;
        return dummy1.next;
    }

clipboard.png
想要了解更多開發技術,面試教程以及互聯網公司內推,歡迎關注個人微信公衆號!將會不按期的發放福利哦~less

相關文章
相關標籤/搜索