本来想用快慢指针做的,就像面试题02.04,交换节点的值,但是这样不能保证每个结点的初始相对位置,于是就只能构造两个链表large和small,分别存放大于x的节点和小于x的节点,再把两个链表拼接起来。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* partition(struct ListNode* head, int x){
//快慢指针,交换顺序
if(head==NULL || head->next==NULL) return head;
struct ListNode* large=(struct ListNode*)malloc(sizeof(struct ListNode));
large->next=NULL; // 如果不加会报错,runtime error: member access within misaligned address
struct ListNode* headl=large;
struct ListNode* small=(struct ListNode*)malloc(sizeof(struct ListNode));
small->next=NULL;
struct ListNode* heads=small;
while(head){
if(head->val <x){
small->next=head;
small=head;
}
else{
large->next=head;
large=head;
}
head=head->next;
}
small->next=headl->next;
large->next=NULL;
return heads->next;
}