/**
* 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;
}
你不需要 保留 每个分区中各节点的初始相对位置。
你这个多一个元素的,很明显是头节点或者结尾节点的判断有问题。
把链表完整的定义、main函数也贴出看看吧