86. 分隔链表

61 阅读1分钟

86. 分隔链表

双dummy节点+双指针:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
#include"stdio.h"
struct ListNode* partition(struct ListNode* head, int x) {
    if (head == NULL || x <= -100 || x >= 100) {
        return head;
    }
    struct ListNode lessHead = {
        .val = 0,
        .next = NULL,
    };
    struct ListNode greatHead = {
        .val = 0,
        .next = NULL,
    };
    
    struct ListNode* lessPtr = &lessHead;
    struct ListNode* greatPtr = &greatHead;
    struct ListNode* currNode = head;
    while (currNode != NULL) {
        if (currNode->val < x) {
            lessPtr->next = currNode;
            lessPtr = lessPtr->next;
        } else {
            greatPtr->next = currNode;
            greatPtr = greatPtr->next;
        }

        struct ListNode* tmpNode = currNode->next;
        currNode->next = NULL;
        currNode = tmpNode;
    }

    lessPtr->next = greatHead.next;
    return lessHead.next;
}
  • 当有需要逐个提取原始链表中的节点到其余散列列表时,节点真正离开原始链表的那刻,要保证自身是散列链表的尾节点(即next节点 = NULLL)。
  • 从栈空间中声明实体变量时,一定要先初始化,一定要先初始化,一定要先初始化。最后代码优化阶段再试着移除初始化。