LeetCode - 0086 - Partition List

題目概要

將鏈表中小于某個值的結點移到鏈表最前方。

原題鏈接

Partition List

題目解析

簡單的數(shù)據結構題,解題思路如下:

  1. 迭代鏈表,將之分為兩部分,一條小于x,一條不小于x
  2. 合并兩條鏈表

復雜度分析

時間復雜度:O(n)
空間復雜度:O(1)

代碼

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
private:
    ListNode* nextNode(ListNode*& head) {
        if (head == NULL)
            return NULL;
        ListNode* current = head;
        head = head->next;
        current->next = NULL;
        return current;
    }
    
    void pushBack(ListNode*& head, ListNode*& tail, ListNode* node) {
        if (head == NULL || tail == NULL) {
            head = tail = node;
            return;
        }
        tail->next = node;
        tail = node;
        return;
    }
    
public:
    ListNode* partition(ListNode* head, int x) {
        if (head == NULL || head->next == NULL)
            return head;
        
        ListNode* less = NULL;
        ListNode* lessTail = NULL;
        ListNode* notLess = NULL;
        ListNode* notLessTail = NULL;
        ListNode* current = NULL;
        
        while(head != NULL) {
            current = nextNode(head);
            if (current->val < x) {
                pushBack(less, lessTail, current);
            }
            else {
                pushBack(notLess, notLessTail, current);
            }
        }
        
        if (less == NULL)
            return notLess;
        
        if (lessTail != NULL)
            lessTail->next = notLess;
        return less;
    }
};

廣告區(qū)域

本人和小伙伴們承接各種軟件項目,有需求的可以聯(lián)系我們。
QQ: 2992073083

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • B樹的定義 一棵m階的B樹滿足下列條件: 樹中每個結點至多有m個孩子。 除根結點和葉子結點外,其它每個結點至少有m...
    文檔隨手記閱讀 13,660評論 0 25
  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,890評論 0 33
  • LeetCode 刷題隨手記 - 第一部分 前 256 題(非會員),僅算法題,的吐槽 https://leetc...
    蕾娜漢默閱讀 18,367評論 2 36
  • 因為之前就復習完數(shù)據結構了,所以為了保持記憶,整理了一份復習綱要,復習的時候可以看著綱要想具體內容。 樹 樹的基本...
    牛富貴兒閱讀 7,503評論 3 10
  • leetcode刷題記錄本文記錄一下leetcode刷題記錄,記錄一下自己的解法和心得。 LeetCode Two...
    EarthChen閱讀 3,599評論 0 6

友情鏈接更多精彩內容