c语言数据结构题 分割链表


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* partition(struct ListNode* head, int x){
    
    struct ListNode* cur = head;
    struct ListNode* lesshead,* lesstail,* greaterhead,* greatertail;
    lesshead = lesstail = greatertail = greaterhead = NULL;
    
    while(cur)
    {
        if(cur->val < x)
        {
            if(lesshead == NULL)
            {
                lesshead = lesstail = cur;
            }
            else
            {
                lesstail->next = cur;
                lesstail = cur;
            }
        }
        else
        {
            if(greaterhead == NULL)
            {
                greaterhead = greatertail = cur;
            }
            else
            {
                greatertail->next = cur;
                    greatertail = cur;
            }
        }
        cur = cur->next;
    }
    lesstail->next = greaterhead;
    greatertail->next = NULL;
    struct ListNode* newNode =(struct ListNode*)malloc(sizeof(struct ListNode));
    
     newNode->next = lesshead;
    return newNode;
}

img


给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。

你不需要 保留 每个分区中各节点的初始相对位置。

  1. 在这里我没有开辟头节点做的,出现这种报错结婚是哪里出问题了呢

你这个多一个元素的,很明显是头节点或者结尾节点的判断有问题。
把链表完整的定义、main函数也贴出看看吧