编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前
给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。
ListNode* partition(ListNode* pHead, int x) {
// write code herew
if (pHead == NULL)
return NULL;
struct ListNode* LH, *GH, *cur, *cur1, *cur2;
LH = (struct ListNode*)malloc(sizeof(struct ListNode));
GH = (struct ListNode*)malloc(sizeof(struct ListNode));
cur = pHead;
cur1 = LH;
cur2 = GH;
while (cur != NULL) {
if (cur->val < x) {
cur1->next = cur;
cur1 = cur;
cur = cur->next;
}
else {
cur2->next = cur;
cur2 = cur;
cur = cur->next;
}
}
cur1->next = GH->next;
cur2->next = NULL;
struct ListNode* tmp = LH;
LH = LH->next;
free(tmp);
free(GH);
return LH;
}