编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前
给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。
解题思路:
1、创建两个头结点,
2、依次将内容分为小于和大于等于于两个链表
3、合并
实现代码:
ListNode* partition(ListNode* pHead, int x) {
if (pHead == NULL){
return NULL;
}
struct ListNode* lh = (struct ListNode*) malloc(sizeof(struct ListNode));
struct ListNode* hh = (struct ListNode*) malloc(sizeof(struct ListNode));
struct ListNode* fh1, *fh2,*newh;
fh1 = lh;
fh2 = hh;
while (pHead) {
if (pHead->val < x) {
fh1->next = pHead;
fh1 = fh1->next;
pHead = pHead->next;
}
else {
fh2->next = pHead;
fh2 = fh2->next;
pHead = pHead->next;
}
}
fh2->next = NULL;
fh1->next = hh->next;
newh = lh->next;
free(hh);
free(lh);
return newh;
}
运行结果: