Leetcode--分隔鏈表

給定一個鏈表和一個特定值 x,對鏈表進行分隔,使得所有小於 x 的節點都在大於或等於 x 的節點之前。

你應當保留兩個分區中每個節點的初始相對位置。

示例:

輸入: head = 1->4->3->2->5->2, x = 3
輸出: 1->2->2->4->3->5

思路

使用兩個僞頭部來記錄小於x的鏈表和大於等於x的鏈表;

最後再將兩個鏈表合併

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {

        // head1爲小於x的節點的頭部,head2爲大於等於x的節點的頭部
        ListNode* head1= new ListNode(0), *h1= head1;
        ListNode* head2= new ListNode(0), *h2= head2;
        while(head){
            if(head->val< x){
                h1->next= head;
                h1= h1->next;
            }
            else{
                h2->next= head;
                h2= h2->next;
            }
            head= head->next;
        }
        // 將大於等於x的鏈表接在小於x的鏈表的後面
        h1->next= head2->next;
        h2->next= NULL;
        return head1->next;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章