题解 | #链表分割#
链表分割
https://www.nowcoder.com/practice/0e27e0b064de4eacac178676ef9c9d70
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class Partition
{
public:
ListNode* partition(ListNode* pHead, int x)
{
ListNode* lesshead, * lesstail, * greaterhead, * greatertail;
lesshead = lesstail = (ListNode*)malloc(sizeof(ListNode));
greaterhead = greatertail = (ListNode*)malloc(sizeof(ListNode));
if (!lesshead || !greaterhead)//检查是否申请成功
{
perror("malloc fail!");
return NULL;
}
ListNode* cur = pHead;//用来遍历旧链表
while (cur)
{
if (cur->val < x)
{
lesstail->next = cur;
lesstail = lesstail->next;
}
else//cur->val >= x
{
greatertail->next = cur;
greatertail = greatertail->next;
}
cur = cur->next;
}
if (lesshead->next == NULL)
{
return greaterhead->next;
}
if (greaterhead->next == NULL)
{
return lesshead->next;
}
lesstail->next = greaterhead->next;//注意是哨兵节点
pHead = lesshead->next;
greatertail->next = NULL;
free(lesshead);
free(greaterhead);
return pHead;
}
};
// ListNode* partition(ListNode* pHead, int x)
// {
// if (!pHead) return NULL;
// ListNode* pNewHead1 = NULL;//指向小链表
// ListNode* cur1 = NULL;//遍历小链表
// ListNode* pNewHead2 = NULL;//指向大链表
// ListNode* cur2 = NULL;//遍历大链表
// ListNode* cur = pHead;//指向旧链表
// while (cur)//遍历旧链表
// {
// if (cur->val < x)//符合要求,尾插到NewHead1
// {
// if (pNewHead1 == NULL)//新链表1为空
// {
// cur1 = pNewHead1 = cur;
// }
// else//新链表不为空
// {
// cur1->next = cur;
// cur1 = cur1->next;
// }
// }
// else//不符合要求,cur->next >= x,尾插到NewHead2
// {
// if (pNewHead2 == NULL)//新链表2为空
// {
// cur2 = pNewHead2 = cur;
// }
// else//新链表不为空
// {
// cur2->next = cur;
// cur2 = cur2->next;
// }
// }
// cur = cur->next;
// }
// if (cur1 == NULL)
// return pNewHead2;
// if (cur2 == NULL)
// return pNewHead1;
// cur1->next = pNewHead2;
// cur2->next = NULL;
// return pNewHead1;
// }
用的是带头节点的单链表
查看5道真题和解析